Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve "variable not found" error message #8474

Merged
merged 6 commits into from
Nov 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,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"]
Loading