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

Improve error message on ds['x', 'y'] #9375

Merged
merged 2 commits into from
Aug 17, 2024
Merged
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
8 changes: 5 additions & 3 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1576,9 +1576,11 @@ def __getitem__(
try:
return self._construct_dataarray(key)
except KeyError as e:
raise KeyError(
f"No variable named {key!r}. Variables on the dataset include {shorten_list_repr(list(self.variables.keys()), max_items=10)}"
) from e
message = f"No variable named {key!r}. 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[{[d for d in key]}]`"
raise KeyError(message) from e

if utils.iterable_of_hashable(key):
return self._copy_listed(key)
Expand Down
5 changes: 5 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -4134,6 +4134,11 @@ def test_getitem(self) -> None:
data["notfound"]
with pytest.raises(KeyError):
data[["var1", "notfound"]]
with pytest.raises(
KeyError,
match=r"Hint: use a list to select multiple variables, for example `ds\[\['var1', 'var2'\]\]`",
):
data["var1", "var2"]

actual1 = data[["var1", "var2"]]
expected1 = Dataset({"var1": data["var1"], "var2": data["var2"]})
Expand Down
Loading