Skip to content

Commit 5871637

Browse files
authored
Do not change coordinate inplace when throwing error (#5957)
1 parent 884f0cb commit 5871637

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

xarray/core/variable.py

+5
Original file line numberDiff line numberDiff line change
@@ -2813,6 +2813,11 @@ def name(self):
28132813
def name(self, value):
28142814
raise AttributeError("cannot modify name of IndexVariable in-place")
28152815

2816+
def _inplace_binary_op(self, other, f):
2817+
raise TypeError(
2818+
"Values of an IndexVariable are immutable and can not be modified inplace"
2819+
)
2820+
28162821

28172822
# for backwards compatibility
28182823
Coordinate = utils.alias(IndexVariable, "Coordinate")

xarray/tests/test_dataarray.py

+12
Original file line numberDiff line numberDiff line change
@@ -1987,6 +1987,18 @@ def test_inplace_math_basics(self):
19871987
assert_array_equal(b.values, x)
19881988
assert source_ndarray(b.values) is x
19891989

1990+
def test_inplace_math_error(self):
1991+
data = np.random.rand(4)
1992+
times = np.arange(4)
1993+
foo = DataArray(data, coords=[times], dims=["time"])
1994+
b = times.copy()
1995+
with pytest.raises(
1996+
TypeError, match=r"Values of an IndexVariable are immutable"
1997+
):
1998+
foo.coords["time"] += 1
1999+
# Check error throwing prevented inplace operation
2000+
assert_array_equal(foo.coords["time"], b)
2001+
19902002
def test_inplace_math_automatic_alignment(self):
19912003
a = DataArray(range(5), [("x", range(5))])
19922004
b = DataArray(range(1, 6), [("x", range(1, 6))])

xarray/tests/test_variable.py

+8
Original file line numberDiff line numberDiff line change
@@ -1656,6 +1656,14 @@ def test_inplace_math(self):
16561656
with pytest.raises(ValueError, match=r"dimensions cannot change"):
16571657
v += Variable("y", np.arange(5))
16581658

1659+
def test_inplace_math_error(self):
1660+
x = np.arange(5)
1661+
v = IndexVariable(["x"], x)
1662+
with pytest.raises(
1663+
TypeError, match=r"Values of an IndexVariable are immutable"
1664+
):
1665+
v += 1
1666+
16591667
def test_reduce(self):
16601668
v = Variable(["x", "y"], self.d, {"ignored": "attributes"})
16611669
assert_identical(v.reduce(np.std, "x"), Variable(["y"], self.d.std(axis=0)))

0 commit comments

Comments
 (0)