Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Include close matches in error message when key not found#30001

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Draft
dstansby wants to merge2 commits intomatplotlib:main
base:main
Choose a base branch
Loading
fromdstansby:close-matches
Draft
Show file tree
Hide file tree
Changes fromall 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: 4 additions & 5 deletionslib/matplotlib/__init__.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -740,12 +740,11 @@ def __setitem__(self, key, val):
and val is rcsetup._auto_backend_sentinel
and "backend" in self):
return
valid_key = _api.check_getitem(
self.validate, rcParam=key, _suggest_close_matches=True, _error_cls=KeyError
)
try:
cval = self.validate[key](val)
except KeyError as err:
raise KeyError(
f"{key} is not a valid rc parameter (see rcParams.keys() for "
f"a list of valid parameters)") from err
cval = valid_key(val)
except ValueError as ve:
raise ValueError(f"Key {key}: {ve}") from None
self._set(key, cval)
Expand Down
23 changes: 19 additions & 4 deletionslib/matplotlib/_api/__init__.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,6 +10,7 @@

"""

import difflib
import functools
import itertools
import pathlib
Expand DownExpand Up@@ -174,12 +175,21 @@ def check_shape(shape, /, **kwargs):
)


def check_getitem(mapping, /, **kwargs):
def check_getitem(
mapping, /, _suggest_close_matches=False, _error_cls=ValueError, **kwargs
Copy link
Member

Choose a reason for hiding this comment

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

Would it make sense the make this depend on the number of elements by default? Suggest if there are more than N keys, otherwise list all. (Choose N somewhere between 5 and 10).

Maybe even don't make this configurable (YAGNI). I feel the automatic decision depending on the number of elements may be all we ever need and we don't need to bother with deciding on the option per call site.

We could always change later because this is private.

story645 and dstansby reacted with thumbs up emoji
):
"""
*kwargs* must consist of a single *key, value* pair. If *key* is in
*mapping*, return ``mapping[value]``; else, raise an appropriate
ValueError.

Parameters
----------
_suggest_close_matches :
If True, suggest only close matches instead of all valid values.
_error_cls :
Class of error to raise.

Examples
--------
>>> _api.check_getitem({"foo": "bar"}, arg=arg)
Expand All@@ -190,9 +200,14 @@ def check_getitem(mapping, /, **kwargs):
try:
return mapping[v]
except KeyError:
raise ValueError(
f"{v!r} is not a valid value for {k}; supported values are "
f"{', '.join(map(repr, mapping))}") from None
if _suggest_close_matches:
if len(best := difflib.get_close_matches(v, mapping.keys(), cutoff=0.5)):
suggestion = f"Did you mean one of {best}?"
else:
suggestion = ""
else:
suggestion = f"Supported values are {', '.join(map(repr, mapping))}"
raise _error_cls(f"{v!r} is not a valid value for {k}. {suggestion}") from None


def caching_module_getattr(cls):
Expand Down
6 changes: 4 additions & 2 deletionslib/matplotlib/_api/__init__.pyi
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
from typing import Any, TypeVar, overload
from typing import Any,Type,TypeVar, overload
from typing_extensions import Self # < Py 3.11

from numpy.typing import NDArray
Expand DownExpand Up@@ -42,7 +42,9 @@ def check_in_list(
values: Sequence[Any], /, *, _print_supported_values: bool = ..., **kwargs: Any
) -> None: ...
def check_shape(shape: tuple[int | None, ...], /, **kwargs: NDArray) -> None: ...
def check_getitem(mapping: Mapping[Any, Any], /, **kwargs: Any) -> Any: ...
def check_getitem(
mapping: Mapping[Any, _T], /, _suggest_close_matches: bool, _error_cls: Type[Exception], **kwargs: Any
) -> _T: ...
def caching_module_getattr(cls: type) -> Callable[[str], Any]: ...
@overload
def define_aliases(
Expand Down
8 changes: 4 additions & 4 deletionslib/matplotlib/cm.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -92,10 +92,10 @@ def __init__(self, cmaps):
self._builtin_cmaps = tuple(cmaps)

def __getitem__(self, item):
try:
returnself._cmaps[item].copy()
except KeyError:
raise KeyError(f"{item!r} is not a known colormap name") from None
cmap = _api.check_getitem(
self._cmaps, colormap=item, _suggest_close_matches=True, _error_cls=KeyError
)
return cmap.copy()

def __iter__(self):
return iter(self._cmaps)
Expand Down
10 changes: 10 additions & 0 deletionslib/matplotlib/tests/test_colors.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1828,3 +1828,13 @@ def test_LinearSegmentedColormap_from_list_value_color_tuple():
cmap([value for value, _ in value_color_tuples]),
to_rgba_array([color for _, color in value_color_tuples]),
)


def test_close_error_name():
with pytest.raises(
KeyError,
match=(
"'grays' is not a valid value for colormap. "
"Did you mean one of ['gray', 'Grays', 'gray_r']?"
)):
matplotlib.colormaps["grays"]
4 changes: 3 additions & 1 deletionlib/matplotlib/tests/test_style.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -140,7 +140,9 @@ def test_context_with_badparam():
with style.context({PARAM: other_value}):
assert mpl.rcParams[PARAM] == other_value
x = style.context({PARAM: original_value, 'badparam': None})
with pytest.raises(KeyError):
with pytest.raises(
KeyError, match="\'badparam\' is not a valid value for rcParam. "
):
with x:
pass
assert mpl.rcParams[PARAM] == other_value
Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp