Skip to content

Commit

Permalink
Improve "variable not found" error message (#8474)
Browse files Browse the repository at this point in the history
* Improve missing variable error message

* [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>
  • Loading branch information
max-sixty and pre-commit-ci[bot] authored Nov 24, 2023
1 parent 398d8e6 commit 71c2f61
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 2 deletions.
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ Bug fixes
Documentation
~~~~~~~~~~~~~

- Improved error message when attempting to get a variable which doesn't exist from a Dataset.
(:pull:`8474`)
By `Maximilian Roos <https://github.com/max-sixty>`_.

Internal Changes
~~~~~~~~~~~~~~~~
Expand Down
10 changes: 9 additions & 1 deletion xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1539,10 +1539,18 @@ def __getitem__(
Indexing with a list of names will return a new ``Dataset`` object.
"""
from xarray.core.formatting import shorten_list_repr

if utils.is_dict_like(key):
return self.isel(**key)
if utils.hashable(key):
return self._construct_dataarray(key)
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

if utils.iterable_of_hashable(key):
return self._copy_listed(key)
raise ValueError(f"Unsupported key-type {type(key)}")
Expand Down
15 changes: 14 additions & 1 deletion xarray/core/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import functools
import math
from collections import defaultdict
from collections.abc import Collection, Hashable
from collections.abc import Collection, Hashable, Sequence
from datetime import datetime, timedelta
from itertools import chain, zip_longest
from reprlib import recursive_repr
Expand Down Expand Up @@ -937,3 +937,16 @@ def diff_dataset_repr(a, b, compat):
summary.append(diff_attrs_repr(a.attrs, b.attrs, compat))

return "\n".join(summary)


def shorten_list_repr(items: Sequence, max_items: int) -> str:
if len(items) <= max_items:
return repr(items)
else:
first_half = repr(items[: max_items // 2])[
1:-1
] # Convert to string and remove brackets
second_half = repr(items[-max_items // 2 :])[
1:-1
] # Convert to string and remove brackets
return f"[{first_half}, ..., {second_half}]"
17 changes: 17 additions & 0 deletions xarray/tests/test_error_messages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"""
This new file is intended to test the quality & friendliness of error messages that are
raised by xarray. It's currently separate from the standard tests, which are more
focused on the functions working (though we could consider integrating them.).
"""

import pytest


def test_no_var_in_dataset(ds):
with pytest.raises(
KeyError,
match=(
r"No variable named 'foo'. Variables on the dataset include \['z1', 'z2', 'x', 'time', 'c', 'y'\]"
),
):
ds["foo"]

0 comments on commit 71c2f61

Please sign in to comment.