Skip to content

Commit

Permalink
Proposal for better error message about in-place operation (#3976)
Browse files Browse the repository at this point in the history
* Improve error message: automatic alignment during in-place operation.

* Sorted imports.

* Fix tests.

* Add suggestions from S. Hoyer.
  • Loading branch information
mancellin authored Jun 24, 2020
1 parent 2a8cd3b commit fb5fe79
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
13 changes: 10 additions & 3 deletions xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
from .formatting import format_item
from .indexes import Indexes, default_indexes, propagate_indexes
from .indexing import is_fancy_indexer
from .merge import PANDAS_TYPES, _extract_indexes_from_coords
from .merge import PANDAS_TYPES, MergeError, _extract_indexes_from_coords
from .options import OPTIONS
from .utils import Default, ReprObject, _check_inplace, _default, either_dict_or_kwargs
from .variable import (
Expand Down Expand Up @@ -2713,8 +2713,15 @@ def func(self, other):
# don't support automatic alignment with in-place arithmetic.
other_coords = getattr(other, "coords", None)
other_variable = getattr(other, "variable", other)
with self.coords._merge_inplace(other_coords):
f(self.variable, other_variable)
try:
with self.coords._merge_inplace(other_coords):
f(self.variable, other_variable)
except MergeError as exc:
raise MergeError(
"Automatic alignment is not supported for in-place operations.\n"
"Consider aligning the indices manually or using a not-in-place operation.\n"
"See https://github.com/pydata/xarray/issues/3910 for more explanations."
) from exc
return self

return func
Expand Down
4 changes: 2 additions & 2 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -1930,9 +1930,9 @@ def test_inplace_math_basics(self):
def test_inplace_math_automatic_alignment(self):
a = DataArray(range(5), [("x", range(5))])
b = DataArray(range(1, 6), [("x", range(1, 6))])
with pytest.raises(xr.MergeError):
with pytest.raises(xr.MergeError, match="Automatic alignment is not supported"):
a += b
with pytest.raises(xr.MergeError):
with pytest.raises(xr.MergeError, match="Automatic alignment is not supported"):
b += a

def test_math_name(self):
Expand Down

0 comments on commit fb5fe79

Please sign in to comment.