diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index 628a2efa61e..c69bc89d1eb 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -115,6 +115,7 @@ is_dict_like, is_duck_array, is_duck_dask_array, + is_list_like, is_scalar, maybe_wrap_array, ) @@ -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) diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index a43e3d15e32..fb3d487f2ef 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -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"]})