Skip to content

Commit 3a28941

Browse files
committed
List coordinates in coords __delitem__ error message, update tests
1 parent 26cb28e commit 3a28941

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

xarray/core/coordinates.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -624,7 +624,9 @@ def __delitem__(self, key: Hashable) -> None:
624624
if key in self:
625625
del self._data[key]
626626
else:
627-
raise KeyError(f"{key!r} is not a coordinate variable.")
627+
raise KeyError(
628+
f"{key!r} is not in coordinate variables {tuple(self.keys())}"
629+
)
628630

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

713715
def __delitem__(self, key: Hashable) -> None:
714716
if key not in self:
715-
raise KeyError(f"{key!r} is not a coordinate variable.")
717+
raise KeyError(
718+
f"{key!r} is not in coordinate variables {tuple(self.keys())}"
719+
)
716720
assert_no_index_corrupted(self._data.xindexes, {key})
717721

718722
del self._data._coords[key]

xarray/tests/test_coordinates.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,12 +82,22 @@ def test_getitem(self) -> None:
8282
DataArray([0, 1, 2], coords={"x": [0, 1, 2]}, name="x"),
8383
)
8484

85-
def test_delitem(self) -> None:
86-
_ds = Dataset(coords={"x": [0, 1, 2]})
87-
coords = Coordinates(coords=_ds.coords, indexes=_ds.xindexes)
85+
@pytest.mark.parametrize("as_dataset", [True, False])
86+
def test_delitem(self, as_dataset: bool) -> None:
87+
if as_dataset:
88+
data = Dataset(coords={"x": [0, 1, 2]})
89+
else:
90+
data = DataArray([1, 2, 3], coords={"x": [0, 1, 2]})
91+
92+
coords = Coordinates(coords=data.coords, indexes=data.xindexes)
8893
del coords["x"]
8994
assert "x" not in coords
9095

96+
with pytest.raises(
97+
KeyError, match="'nonexistent' is not in coordinate variables"
98+
):
99+
del coords["nonexistent"]
100+
91101
def test_update(self) -> None:
92102
_ds = Dataset(coords={"x": [0, 1, 2]})
93103
coords = Coordinates(coords=_ds.coords, indexes=_ds.xindexes)

0 commit comments

Comments
 (0)