diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py index 63cba53b689..0ec8b86fa39 100644 --- a/xarray/core/dataarray.py +++ b/xarray/core/dataarray.py @@ -54,7 +54,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 ( @@ -2663,8 +2663,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 diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py index c3e5aafabfe..d51fc10d85c 100644 --- a/xarray/tests/test_dataarray.py +++ b/xarray/tests/test_dataarray.py @@ -1921,9 +1921,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):