Skip to content

Commit fb5fe79

Browse files
authored
Proposal for better error message about in-place operation (#3976)
* Improve error message: automatic alignment during in-place operation. * Sorted imports. * Fix tests. * Add suggestions from S. Hoyer.
1 parent 2a8cd3b commit fb5fe79

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

xarray/core/dataarray.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@
5353
from .formatting import format_item
5454
from .indexes import Indexes, default_indexes, propagate_indexes
5555
from .indexing import is_fancy_indexer
56-
from .merge import PANDAS_TYPES, _extract_indexes_from_coords
56+
from .merge import PANDAS_TYPES, MergeError, _extract_indexes_from_coords
5757
from .options import OPTIONS
5858
from .utils import Default, ReprObject, _check_inplace, _default, either_dict_or_kwargs
5959
from .variable import (
@@ -2713,8 +2713,15 @@ def func(self, other):
27132713
# don't support automatic alignment with in-place arithmetic.
27142714
other_coords = getattr(other, "coords", None)
27152715
other_variable = getattr(other, "variable", other)
2716-
with self.coords._merge_inplace(other_coords):
2717-
f(self.variable, other_variable)
2716+
try:
2717+
with self.coords._merge_inplace(other_coords):
2718+
f(self.variable, other_variable)
2719+
except MergeError as exc:
2720+
raise MergeError(
2721+
"Automatic alignment is not supported for in-place operations.\n"
2722+
"Consider aligning the indices manually or using a not-in-place operation.\n"
2723+
"See https://github.com/pydata/xarray/issues/3910 for more explanations."
2724+
) from exc
27182725
return self
27192726

27202727
return func

xarray/tests/test_dataarray.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1930,9 +1930,9 @@ def test_inplace_math_basics(self):
19301930
def test_inplace_math_automatic_alignment(self):
19311931
a = DataArray(range(5), [("x", range(5))])
19321932
b = DataArray(range(1, 6), [("x", range(1, 6))])
1933-
with pytest.raises(xr.MergeError):
1933+
with pytest.raises(xr.MergeError, match="Automatic alignment is not supported"):
19341934
a += b
1935-
with pytest.raises(xr.MergeError):
1935+
with pytest.raises(xr.MergeError, match="Automatic alignment is not supported"):
19361936
b += a
19371937

19381938
def test_math_name(self):

0 commit comments

Comments
 (0)