Skip to content

Backport PR #19571 on branch v3.4.x (Fail early when setting Text color to a non-colorlike.) #19617

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 2 additions & 4 deletions lib/matplotlib/lines.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
5 changes: 5 additions & 0 deletions lib/matplotlib/tests/test_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
4 changes: 4 additions & 0 deletions lib/matplotlib/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down