From a057e30cfd06d839a21718fa9b4cb5ea065ae83c Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Sat, 27 Feb 2021 18:49:08 +0100 Subject: [PATCH] Backport PR #19571: Fail early when setting Text color to a non-colorlike. --- lib/matplotlib/colors.py | 9 +++++++++ lib/matplotlib/lines.py | 6 ++---- lib/matplotlib/tests/test_text.py | 5 +++++ lib/matplotlib/text.py | 4 ++++ 4 files changed, 20 insertions(+), 4 deletions(-) diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index 943008f92afc..0176d60206d6 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -147,6 +147,15 @@ def is_color_like(c): return True +def _check_color_like(**kwargs): + """ + For each *key, value* pair in *kwargs*, check that *value* is color-like. + """ + for k, v in kwargs.items(): + if not is_color_like(v): + raise ValueError(f"{v!r} is not a valid value for {k}") + + def same_color(c1, c2): """ Return whether the colors *c1* and *c2* are the same. diff --git a/lib/matplotlib/lines.py b/lib/matplotlib/lines.py index 585e92e61c51..7fad0c59f0e2 100644 --- a/lib/matplotlib/lines.py +++ b/lib/matplotlib/lines.py @@ -13,7 +13,6 @@ from .artist import Artist, allow_rasterization from .cbook import ( _to_unmasked_float_array, ls_mapper, ls_mapper_r, STEP_LOOKUP_MAP) -from .colors import is_color_like, get_named_colors_mapping from .markers import MarkerStyle from .path import Path from .transforms import Bbox, BboxTransformTo, TransformedPath @@ -1050,9 +1049,8 @@ def set_color(self, color): ---------- color : color """ - if not is_color_like(color) and color != 'auto': - _api.check_in_list(get_named_colors_mapping(), - _print_supported_values=False, color=color) + if not cbook._str_equal(color, 'auto'): + mcolors._check_color_like(color=color) self._color = color self.stale = True diff --git a/lib/matplotlib/tests/test_text.py b/lib/matplotlib/tests/test_text.py index 1fbbf864e25c..72fec721a43a 100644 --- a/lib/matplotlib/tests/test_text.py +++ b/lib/matplotlib/tests/test_text.py @@ -709,3 +709,8 @@ def test_update_mutate_input(): t.update(inp) assert inp['fontproperties'] == cache['fontproperties'] assert inp['bbox'] == cache['bbox'] + + +def test_invalid_color(): + with pytest.raises(ValueError): + plt.figtext(.5, .5, "foo", c="foobar") diff --git a/lib/matplotlib/text.py b/lib/matplotlib/text.py index c272dfc7858d..1714cc5901c4 100644 --- a/lib/matplotlib/text.py +++ b/lib/matplotlib/text.py @@ -934,6 +934,10 @@ def set_color(self, color): ---------- color : color """ + # "auto" is only supported by axisartist, but we can just let it error + # out at draw time for simplicity. + if not cbook._str_equal(color, "auto"): + mpl.colors._check_color_like(color=color) # Make sure it is hashable, or get_prop_tup will fail. try: hash(color)