Skip to content

Commit e8c7826

Browse files
committed
Fix parsing color as sequence of ints 0-255
1 parent 6d215d4 commit e8c7826

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

branca/colormap.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,9 @@ def _color_float_to_int(x: float) -> int:
5656

5757

5858
def _parse_color(x: Union[tuple, list, str]) -> TypeRGBAFloats:
59+
"""Convert an unknown color value to an RGBA tuple between 0 and 1."""
5960
if isinstance(x, (tuple, list)):
60-
return tuple(tuple(x) + (1.0,))[:4] # type: ignore
61+
return _parse_color_as_numerical_sequence(x)
6162
elif isinstance(x, str) and _is_hex(x):
6263
return _parse_hex(x)
6364
elif isinstance(x, str):
@@ -69,6 +70,23 @@ def _parse_color(x: Union[tuple, list, str]) -> TypeRGBAFloats:
6970
raise ValueError(f"Unrecognized color code {x!r}")
7071

7172

73+
def _parse_color_as_numerical_sequence(x: Union[tuple, list]) -> TypeRGBAFloats:
74+
"""Convert a color as a sequence of numbers to an RGBA tuple between 0 and 1."""
75+
if not 3 <= len(x) <= 4:
76+
raise ValueError(f"Color sequence should have 3 or 4 elements, not {len(x)}.")
77+
color: List[float] = []
78+
for value in x:
79+
if isinstance(value, int):
80+
color.append(_color_int_to_float(value))
81+
elif isinstance(value, float):
82+
color.append(value)
83+
else:
84+
raise TypeError(f"Unexpected type in color sequence: {type(value)}.")
85+
if len(color) == 3:
86+
color.append(1.0) # add alpha channel
87+
return tuple(color) # type: ignore
88+
89+
7290
def _base(x: float) -> float:
7391
if x > 0:
7492
base = pow(10, math.floor(math.log10(x)))

0 commit comments

Comments
 (0)