Skip to content
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

Suggest the correct name when no key matches in the dataset #9943

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
9 changes: 8 additions & 1 deletion xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1610,7 +1610,14 @@ def __getitem__(
try:
return self._construct_dataarray(key)
except KeyError as e:
message = f"No variable named {key!r}. Variables on the dataset include {shorten_list_repr(list(self.variables.keys()), max_items=10)}"
message = f"No variable named {key!r}."

best_guess = utils.did_you_mean(key, self.variables.keys())
Copy link
Contributor

Choose a reason for hiding this comment

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

Amazing idea. I would print the best guess first, and then any others so that's it's easy to see

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Maybe should just remove the "Variables on the dataset include ..." ? They try to do the same thing I think.

Copy link
Contributor

Choose a reason for hiding this comment

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

Yeah you could sort the whole list by similarity and then print that (truncated as above)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Now it prioritizes best_guess. If best_guess is empty you could be working in the wrong dataset, so it's still nice to get some kind of clue which dataset you're using.

if best_guess:
message += f" {best_guess}"
else:
message += f" Variables on the dataset include {shorten_list_repr(list(self.variables.keys()), max_items=10)}"

# If someone attempts `ds['foo' , 'bar']` instead of `ds[['foo', 'bar']]`
if isinstance(key, tuple):
message += f"\nHint: use a list to select multiple variables, for example `ds[{list(key)}]`"
Expand Down
42 changes: 42 additions & 0 deletions xarray/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from __future__ import annotations

import contextlib
import difflib
import functools
import importlib
import inspect
Expand Down Expand Up @@ -114,6 +115,47 @@ def wrapper(*args, **kwargs):
return wrapper


def did_you_mean(
word: Hashable, possibilities: Iterable[Hashable], *, n: int = 10
) -> str:
"""
Suggest a few correct words based on a list of possibilites

Parameters
----------
word : Hashable
Word to compare to a list of possibilites.
possibilities : Iterable of Hashable
The iterable of Hashable that contains the correct values.
n : int, default: 10
Maximum number of suggestions to show.

Examples
--------
>>> did_you_mean("bluch", ("blech", "gray_r", 1, None, (2, 56)))
"Did you mean one of ('blech',)?"
>>> did_you_mean("none", ("blech", "gray_r", 1, None, (2, 56)))
'Did you mean one of (None,)?'

See also
--------
https://en.wikipedia.org/wiki/String_metric
"""
# Convert all values to string, get_close_matches doesn't handle all hashables:
possibilites_str: dict[str, Hashable] = {str(k): k for k in possibilities}

msg = ""
if len(
best_str := difflib.get_close_matches(
str(word), list(possibilites_str.keys()), n=n
)
):
best = tuple(possibilites_str[k] for k in best_str)
msg = f"Did you mean one of {best}?"

return msg


def get_valid_numpy_dtype(array: np.ndarray | pd.Index) -> np.dtype:
"""Return a numpy compatible dtype from either
a numpy array or a pandas.Index.
Expand Down
Loading