Skip to content
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

Do not change coordinate inplace when throwing error #5957

Merged
merged 3 commits into from
Nov 9, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -2418,6 +2418,10 @@ def _inplace_binary_op(self, other, f):
if dims != self.dims:
raise ValueError("dimensions cannot change for in-place operations")
with np.errstate(all="ignore"):
# Give a chance to Variable.values.setter to throw error if needed
# without updating self_data inplace
if isinstance(self_data, np.ndarray):
self.values = f(self_data.copy(), other_data)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Defensively copying xarray.Variable data would negate the main purpose of in-place binary arithmetic, which is to avoid copies.

For fixing #5036, what about instead overriding _inplace_binary_op on the IndexVariable subclass? I think we could just make it raise a TypeError instead of attempting to do the computation.

self.values = f(self_data, other_data)
return self

Expand Down
10 changes: 10 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -1987,6 +1987,16 @@ 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(ValueError, match=r"Cannot assign to the .values"):
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