11from dataclasses import dataclass
2+ from functools import cached_property
23from typing import Optional
34
45import numpy as np
@@ -36,11 +37,10 @@ def __init__(self):
3637 @staticmethod
3738 def _random_hexcolor () -> str :
3839 """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 } "
4041
4142 def regenerate_color_palette (self , seaborn_palettes : Optional [list [str ]] = None ):
4243 try :
43-
4444 import seaborn as sns
4545 seaborn_installed = True
4646 except ImportError :
@@ -54,7 +54,7 @@ def regenerate_color_palette(self, seaborn_palettes: Optional[list[str]] = None)
5454 elif seaborn_palettes and not seaborn_installed :
5555 raise ImportError ("Seaborn is not installed. Please install it to use color palettes." )
5656 else :
57- hex_colors = self ._gempy_default_colors
57+ hex_colors = list ( self ._gempy_default_colors )
5858
5959 self .hex_colors = hex_colors
6060
@@ -65,14 +65,18 @@ def __iter__(self) -> 'ColorsGenerator':
6565
6666 def __next__ (self ) -> str :
6767 """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
7272
73- while True :
74- return self ._random_hexcolor ()
75-
7673 def up_next (self ) -> str :
7774 """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