Skip to content

_check_color_like function for list inputs #25025

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

Closed
wants to merge 23 commits into from
Closed
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
12 changes: 12 additions & 0 deletions lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,18 @@ def _check_color_like(**kwargs):
raise ValueError(f"{v!r} is not a valid value for {k}")


def _check_color_like_list(**kwargs):
"""
For each *key, lst* pair in *kwargs*, check that every
element *v* in *lst* is color-like.
"""
for k, lst in kwargs.items():
invalid_col = [c for c in lst if not is_color_like(c)]
if invalid_col:
err_msg = f"{invalid_col!r} are not valid values for {k}"
raise ValueError(err_msg)


def same_color(c1, c2):
"""
Return whether the colors *c1* and *c2* are the same.
Expand Down
18 changes: 18 additions & 0 deletions lib/matplotlib/tests/test_colors.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import copy
import itertools
import unittest.mock
from re import escape

from io import BytesIO
import numpy as np
Expand Down Expand Up @@ -1592,3 +1593,20 @@ def test_cm_set_cmap_error():
bad_cmap = 'AardvarksAreAwkward'
with pytest.raises(ValueError, match=bad_cmap):
sm.set_cmap(bad_cmap)


def test_check_color_like():
err_msg = "['abcd'] is not a valid value for c"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm pretty sure this error message isn't a list because the input to this function isn't a list

assert mcolors._check_color_like(colors1='yellow', colors2='red') is None
with pytest.raises(ValueError, match=err_msg):
mcolors._check_color_like(c='abcd')


def test_check_color_like_list():
err_msg = escape("['abcd'] are not valid values for c")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should be able to use r" instead of escape but if using escape then please write re.escape and import re rather than from re import escape

assert mcolors._check_color_like_list(colors=['yellow', 'orange']) is None
assert mcolors._check_color_like_list(c1=['red'], c2=['blue']) is None
with pytest.raises(ValueError, match=err_msg):
mcolors._check_color_like_list(c=['abcd', 'red'])
with pytest.raises(ValueError, match=err_msg):
mcolors._check_color_like_list(c1=['red', 'blue'], c=['abcd'])