diff --git a/xarray/core/variable.py b/xarray/core/variable.py index a96adb31e64..52125ec4113 100644 --- a/xarray/core/variable.py +++ b/xarray/core/variable.py @@ -2813,6 +2813,11 @@ def name(self): def name(self, value): raise AttributeError("cannot modify name of IndexVariable in-place") + def _inplace_binary_op(self, other, f): + raise TypeError( + "Values of an IndexVariable are immutable and can not be modified inplace" + ) + # for backwards compatibility Coordinate = utils.alias(IndexVariable, "Coordinate") diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py index 53c650046e7..5e9c1b87ce2 100644 --- a/xarray/tests/test_dataarray.py +++ b/xarray/tests/test_dataarray.py @@ -1987,6 +1987,18 @@ def test_inplace_math_basics(self): assert_array_equal(b.values, x) assert source_ndarray(b.values) is x + def test_inplace_math_error(self): + data = np.random.rand(4) + times = np.arange(4) + foo = DataArray(data, coords=[times], dims=["time"]) + b = times.copy() + with pytest.raises( + TypeError, match=r"Values of an IndexVariable are immutable" + ): + foo.coords["time"] += 1 + # Check error throwing prevented inplace operation + assert_array_equal(foo.coords["time"], b) + def test_inplace_math_automatic_alignment(self): a = DataArray(range(5), [("x", range(5))]) b = DataArray(range(1, 6), [("x", range(1, 6))]) diff --git a/xarray/tests/test_variable.py b/xarray/tests/test_variable.py index 9c0e45c5da9..3267af8b45b 100644 --- a/xarray/tests/test_variable.py +++ b/xarray/tests/test_variable.py @@ -1656,6 +1656,14 @@ def test_inplace_math(self): with pytest.raises(ValueError, match=r"dimensions cannot change"): v += Variable("y", np.arange(5)) + def test_inplace_math_error(self): + x = np.arange(5) + v = IndexVariable(["x"], x) + with pytest.raises( + TypeError, match=r"Values of an IndexVariable are immutable" + ): + v += 1 + def test_reduce(self): v = Variable(["x", "y"], self.d, {"ignored": "attributes"}) assert_identical(v.reduce(np.std, "x"), Variable(["y"], self.d.std(axis=0)))