Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork7.9k
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
base:main
Are you sure you want to change the base?
Uh oh!
There was an error while loading.Please reload this page.
Changes fromall commits
File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -10,6 +10,7 @@ | ||
""" | ||
import difflib | ||
import functools | ||
import itertools | ||
import pathlib | ||
@@ -174,12 +175,21 @@ def check_shape(shape, /, **kwargs): | ||
) | ||
def check_getitem( | ||
mapping, /, _suggest_close_matches=False, _error_cls=ValueError, **kwargs | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. | ||
): | ||
""" | ||
*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) | ||
@@ -190,9 +200,14 @@ def check_getitem(mapping, /, **kwargs): | ||
try: | ||
return mapping[v] | ||
except KeyError: | ||
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): | ||
Uh oh!
There was an error while loading.Please reload this page.