Skip to content

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

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

Merged
merged 9 commits into from
Jan 17, 2025
Merged
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
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
@@ -52,6 +52,8 @@ New Features
~~~~~~~~~~~~
- Relax nanosecond datetime restriction in CF time decoding (:issue:`7493`, :pull:`9618`).
By `Kai Mühlbauer <https://github.com/kmuehlbauer>`_ and `Spencer Clark <https://github.com/spencerkclark>`_.
- Improve the error message raised when no key is matching the available variables in a dataset. (:pull:`9943`)
By `Jimmy Westling <https://github.com/illviljan>`_.

Breaking changes
~~~~~~~~~~~~~~~~
9 changes: 8 additions & 1 deletion xarray/core/dataset.py
Original file line number Diff line number Diff line change
@@ -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)}]`"
42 changes: 42 additions & 0 deletions xarray/core/utils.py
Original file line number Diff line number Diff line change
@@ -37,6 +37,7 @@
from __future__ import annotations

import contextlib
import difflib
import functools
import importlib
import inspect
@@ -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.

Unchanged files with check annotations Beta

# Flaky test. Very open to contributions on fixing this
@pytest.mark.flaky
def test_roundtrip_coordinates(self) -> None:
super().test_roundtrip_coordinates()

Check failure on line 2278 in xarray/tests/test_backends.py

GitHub Actions / ubuntu-latest py3.12 flaky

TestNetCDF4ViaDaskData.test_roundtrip_coordinates Failed: Timeout >180.0s
@requires_zarr
def test_dask_roundtrip(self) -> None:
with create_tmp_file() as tmp:
data = create_test_data()
data.to_netcdf(tmp)

Check failure on line 5092 in xarray/tests/test_backends.py

GitHub Actions / ubuntu-latest py3.12 flaky

TestDask.test_dask_roundtrip Failed: Timeout >180.0s
chunks = {"dim1": 4, "dim2": 4, "dim3": 4, "time": 10}
with open_dataset(tmp, chunks=chunks) as dask_ds:
assert_identical(data, dask_ds)