Skip to content

Commit 0851574

Browse files
authored
Merge pull request #15834 from anntzer/to_rgba
Optimize colors.to_rgba.
2 parents 2555e38 + 1cbf8ff commit 0851574

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

lib/matplotlib/colors.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
from collections.abc import Sized
6969
import functools
7070
import itertools
71+
from numbers import Number
7172
import re
7273

7374
import numpy as np
@@ -260,16 +261,16 @@ def _to_rgba_no_colorcycle(c, alpha=None):
260261
return c, c, c, alpha if alpha is not None else 1.
261262
raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
262263
# tuple color.
263-
c = np.array(c)
264-
if not np.can_cast(c.dtype, float, "same_kind") or c.ndim != 1:
265-
# Test the dtype explicitly as `map(float, ...)`, `np.array(...,
266-
# float)` and `np.array(...).astype(float)` all convert "0.5" to 0.5.
267-
# Test dimensionality to reject single floats.
264+
if not np.iterable(c):
268265
raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
269-
# Return a tuple to prevent the cached value from being modified.
270-
c = tuple(c.astype(float))
271266
if len(c) not in [3, 4]:
272267
raise ValueError("RGBA sequence should have length 3 or 4")
268+
if not all(isinstance(x, Number) for x in c):
269+
# Checks that don't work: `map(float, ...)`, `np.array(..., float)` and
270+
# `np.array(...).astype(float)` would all convert "0.5" to 0.5.
271+
raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
272+
# Return a tuple to prevent the cached value from being modified.
273+
c = tuple(map(float, c))
273274
if len(c) == 3 and alpha is None:
274275
alpha = 1
275276
if alpha is not None:

0 commit comments

Comments
 (0)