Skip to content
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
16 changes: 15 additions & 1 deletion lib/matplotlib/_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ def check_in_list(values, /, *, _print_supported_values=True, **kwargs):
----------
values : iterable
Sequence of values to check on.

Note: All values must support == comparisons.
This means in particular the entries must not be numpy arrays.
_print_supported_values : bool, default: True
Whether to print *values* when raising ValueError.
**kwargs : dict
Expand All @@ -133,7 +136,18 @@ def check_in_list(values, /, *, _print_supported_values=True, **kwargs):
if not kwargs:
raise TypeError("No argument to check!")
for key, val in kwargs.items():
if val not in values:
try:
exists = val in values
except ValueError:
# `in` internally uses `val == values[i]`. There are some objects
# that do not support == to arbitrary other objects, in particular
# numpy arrays.
# Since such objects are not allowed in values, we can gracefully
# handle the case that val (typically provided by users) is of such
# type and directly state it's not in the list instead of letting
# the individual `val == values[i]` ValueError surface.
exists = False
if not exists:
msg = f"{val!r} is not a valid value for {key}"
if _print_supported_values:
msg += f"; supported values are {', '.join(map(repr, values))}"
Expand Down
5 changes: 5 additions & 0 deletions lib/matplotlib/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,8 @@ def f() -> None:
def test_empty_check_in_list() -> None:
with pytest.raises(TypeError, match="No argument to check!"):
_api.check_in_list(["a"])


def test_check_in_list_numpy() -> None:
with pytest.raises(ValueError, match=r"array\(5\) is not a valid value"):
_api.check_in_list(['a', 'b'], value=np.array(5))
Loading