Skip to content

Commit da9e7ec

Browse files
Improve error message on ds['x', 'y'] (#9375)
* Improve error message on `ds['x', 'y']` While trying to help with #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 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 5693ac7 commit da9e7ec

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

xarray/core/dataset.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -1576,9 +1576,11 @@ def __getitem__(
15761576
try:
15771577
return self._construct_dataarray(key)
15781578
except KeyError as e:
1579-
raise KeyError(
1580-
f"No variable named {key!r}. Variables on the dataset include {shorten_list_repr(list(self.variables.keys()), max_items=10)}"
1581-
) from e
1579+
message = f"No variable named {key!r}. Variables on the dataset include {shorten_list_repr(list(self.variables.keys()), max_items=10)}"
1580+
# If someone attempts `ds['foo' , 'bar']` instead of `ds[['foo', 'bar']]`
1581+
if isinstance(key, tuple):
1582+
message += f"\nHint: use a list to select multiple variables, for example `ds[{[d for d in key]}]`"
1583+
raise KeyError(message) from e
15821584

15831585
if utils.iterable_of_hashable(key):
15841586
return self._copy_listed(key)

xarray/tests/test_dataset.py

+5
Original file line numberDiff line numberDiff line change
@@ -4134,6 +4134,11 @@ def test_getitem(self) -> None:
41344134
data["notfound"]
41354135
with pytest.raises(KeyError):
41364136
data[["var1", "notfound"]]
4137+
with pytest.raises(
4138+
KeyError,
4139+
match=r"Hint: use a list to select multiple variables, for example `ds\[\['var1', 'var2'\]\]`",
4140+
):
4141+
data["var1", "var2"]
41374142

41384143
actual1 = data[["var1", "var2"]]
41394144
expected1 = Dataset({"var1": data["var1"], "var2": data["var2"]})

0 commit comments

Comments
 (0)