Skip to content

Commit

Permalink
List coordinates in coords __delitem__ error message, update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mgunyho committed Aug 19, 2023
1 parent 26cb28e commit 3a28941
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
8 changes: 6 additions & 2 deletions xarray/core/coordinates.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,9 @@ def __delitem__(self, key: Hashable) -> None:
if key in self:
del self._data[key]
else:
raise KeyError(f"{key!r} is not a coordinate variable.")
raise KeyError(
f"{key!r} is not in coordinate variables {tuple(self.keys())}"
)

def _ipython_key_completions_(self):
"""Provide method for the key-autocompletions in IPython."""
Expand Down Expand Up @@ -712,7 +714,9 @@ def to_dataset(self) -> Dataset:

def __delitem__(self, key: Hashable) -> None:
if key not in self:
raise KeyError(f"{key!r} is not a coordinate variable.")
raise KeyError(
f"{key!r} is not in coordinate variables {tuple(self.keys())}"
)
assert_no_index_corrupted(self._data.xindexes, {key})

del self._data._coords[key]
Expand Down
16 changes: 13 additions & 3 deletions xarray/tests/test_coordinates.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,22 @@ def test_getitem(self) -> None:
DataArray([0, 1, 2], coords={"x": [0, 1, 2]}, name="x"),
)

def test_delitem(self) -> None:
_ds = Dataset(coords={"x": [0, 1, 2]})
coords = Coordinates(coords=_ds.coords, indexes=_ds.xindexes)
@pytest.mark.parametrize("as_dataset", [True, False])
def test_delitem(self, as_dataset: bool) -> None:
if as_dataset:
data = Dataset(coords={"x": [0, 1, 2]})
else:
data = DataArray([1, 2, 3], coords={"x": [0, 1, 2]})

coords = Coordinates(coords=data.coords, indexes=data.xindexes)
del coords["x"]
assert "x" not in coords

with pytest.raises(
KeyError, match="'nonexistent' is not in coordinate variables"
):
del coords["nonexistent"]

def test_update(self) -> None:
_ds = Dataset(coords={"x": [0, 1, 2]})
coords = Coordinates(coords=_ds.coords, indexes=_ds.xindexes)
Expand Down

0 comments on commit 3a28941

Please sign in to comment.