From 90c089d4a41ff864dd508089dc14f00cb82aaf07 Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Sat, 1 Nov 2025 13:01:58 +0100 Subject: [PATCH] FIX: Gracefully handle numpy arrays as input to check_in_list() Closes #30706 --- lib/matplotlib/_api/__init__.py | 16 +++++++++++++++- lib/matplotlib/tests/test_api.py | 5 +++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/lib/matplotlib/_api/__init__.py b/lib/matplotlib/_api/__init__.py index 39496cfb0e82..216cc885ea24 100644 --- a/lib/matplotlib/_api/__init__.py +++ b/lib/matplotlib/_api/__init__.py @@ -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 @@ -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))}" diff --git a/lib/matplotlib/tests/test_api.py b/lib/matplotlib/tests/test_api.py index 58e7986bfce6..4d0241264ddb 100644 --- a/lib/matplotlib/tests/test_api.py +++ b/lib/matplotlib/tests/test_api.py @@ -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))