Skip to content

Commit

Permalink
Improve error message on ds['x', 'y']
Browse files Browse the repository at this point in the history
While trying to help with pydata#9372, I realize the error message for this could be much better, and so putting this PR in as some penance for my tardiness in helping there
  • Loading branch information
max-sixty committed Aug 17, 2024
1 parent 5693ac7 commit 7e42794
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
9 changes: 6 additions & 3 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@
is_dict_like,
is_duck_array,
is_duck_dask_array,
is_list_like,
is_scalar,
maybe_wrap_array,
)
Expand Down Expand Up @@ -1576,9 +1577,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

0 comments on commit 7e42794

Please sign in to comment.