Skip to content

Commit 71c2f61

Browse files
Improve "variable not found" error message (#8474)
* 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>
1 parent 398d8e6 commit 71c2f61

File tree

4 files changed

+43
-2
lines changed

4 files changed

+43
-2
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,9 @@ Bug fixes
4646
Documentation
4747
~~~~~~~~~~~~~
4848

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

5053
Internal Changes
5154
~~~~~~~~~~~~~~~~

xarray/core/dataset.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1539,10 +1539,18 @@ def __getitem__(
15391539
15401540
Indexing with a list of names will return a new ``Dataset`` object.
15411541
"""
1542+
from xarray.core.formatting import shorten_list_repr
1543+
15421544
if utils.is_dict_like(key):
15431545
return self.isel(**key)
15441546
if utils.hashable(key):
1545-
return self._construct_dataarray(key)
1547+
try:
1548+
return self._construct_dataarray(key)
1549+
except KeyError as e:
1550+
raise KeyError(
1551+
f"No variable named {key!r}. Variables on the dataset include {shorten_list_repr(list(self.variables.keys()), max_items=10)}"
1552+
) from e
1553+
15461554
if utils.iterable_of_hashable(key):
15471555
return self._copy_listed(key)
15481556
raise ValueError(f"Unsupported key-type {type(key)}")

xarray/core/formatting.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import functools
77
import math
88
from collections import defaultdict
9-
from collections.abc import Collection, Hashable
9+
from collections.abc import Collection, Hashable, Sequence
1010
from datetime import datetime, timedelta
1111
from itertools import chain, zip_longest
1212
from reprlib import recursive_repr
@@ -937,3 +937,16 @@ def diff_dataset_repr(a, b, compat):
937937
summary.append(diff_attrs_repr(a.attrs, b.attrs, compat))
938938

939939
return "\n".join(summary)
940+
941+
942+
def shorten_list_repr(items: Sequence, max_items: int) -> str:
943+
if len(items) <= max_items:
944+
return repr(items)
945+
else:
946+
first_half = repr(items[: max_items // 2])[
947+
1:-1
948+
] # Convert to string and remove brackets
949+
second_half = repr(items[-max_items // 2 :])[
950+
1:-1
951+
] # Convert to string and remove brackets
952+
return f"[{first_half}, ..., {second_half}]"

xarray/tests/test_error_messages.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
"""
2+
This new file is intended to test the quality & friendliness of error messages that are
3+
raised by xarray. It's currently separate from the standard tests, which are more
4+
focused on the functions working (though we could consider integrating them.).
5+
"""
6+
7+
import pytest
8+
9+
10+
def test_no_var_in_dataset(ds):
11+
with pytest.raises(
12+
KeyError,
13+
match=(
14+
r"No variable named 'foo'. Variables on the dataset include \['z1', 'z2', 'x', 'time', 'c', 'y'\]"
15+
),
16+
):
17+
ds["foo"]

0 commit comments

Comments
 (0)