1
1
from dataclasses import dataclass
2
+ from functools import cached_property
2
3
from typing import Optional
3
4
4
5
import numpy as np
@@ -36,11 +37,10 @@ def __init__(self):
36
37
@staticmethod
37
38
def _random_hexcolor () -> str :
38
39
"""Generates a random hex color string."""
39
- return "#" + str ( hex ( np .random .randint (0 , 16777215 ))). lstrip ( "0x" )
40
+ return f"# { np .random .randint (0 , 0xffffff ):06x } "
40
41
41
42
def regenerate_color_palette (self , seaborn_palettes : Optional [list [str ]] = None ):
42
43
try :
43
-
44
44
import seaborn as sns
45
45
seaborn_installed = True
46
46
except ImportError :
@@ -54,7 +54,7 @@ def regenerate_color_palette(self, seaborn_palettes: Optional[list[str]] = None)
54
54
elif seaborn_palettes and not seaborn_installed :
55
55
raise ImportError ("Seaborn is not installed. Please install it to use color palettes." )
56
56
else :
57
- hex_colors = self ._gempy_default_colors
57
+ hex_colors = list ( self ._gempy_default_colors )
58
58
59
59
self .hex_colors = hex_colors
60
60
@@ -65,14 +65,18 @@ def __iter__(self) -> 'ColorsGenerator':
65
65
66
66
def __next__ (self ) -> str :
67
67
"""Generator that yields the next color."""
68
- for color in self .hex_colors :
69
- result = self .hex_colors [ self . _index ]
70
- self ._index += 1
71
- return result
68
+ color = self .up_next ()
69
+ self ._index += 1
70
+ del self ._next_color
71
+ return color
72
72
73
- while True :
74
- return self ._random_hexcolor ()
75
-
76
73
def up_next (self ) -> str :
77
74
"""Returns the next color without incrementing the index."""
78
- return self .hex_colors [self ._index ]
75
+ return self ._next_color
76
+
77
+ @cached_property
78
+ def _next_color (self ) -> str :
79
+ if self ._index < len (self .hex_colors ):
80
+ return self .hex_colors [self ._index ]
81
+
82
+ return self ._random_hexcolor ()
0 commit comments