Skip to content

Do not change coordinate inplace when throwing error #5957

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

Merged
merged 3 commits into from
Nov 9, 2021
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
5 changes: 5 additions & 0 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
12 changes: 12 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))])
Expand Down
8 changes: 8 additions & 0 deletions xarray/tests/test_variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
Expand Down