Skip to content

Commit 4880012

Browse files
benbovydcherian
andauthored
Fix aligned index variable metadata side effect (#6857)
* alignment: fix index variable metadata side effect * add regression test * assert no side effect on original objects * update what's new Co-authored-by: Deepak Cherian <[email protected]>
1 parent 0496cb4 commit 4880012

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

doc/whats-new.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ Bug fixes
4646
By `Jimmy Westling <https://github.com/illviljan>`_.
4747
- Fix incompatibility with numpy 1.20 (:issue:`6818`, :pull:`6821`)
4848
By `Michael Niklas <https://github.com/headtr1ck>`_.
49+
- Fix side effects on index coordinate metadata after aligning objects. (:issue:`6852`, :pull:`6857`)
50+
By `Benoît Bovy <https://github.com/benbovy>`_.
4951
- Make FacetGrid.set_titles send kwargs correctly using `handle.udpate(kwargs)`.
5052
(:issue:`6839`, :pull:`6843`)
5153
By `Oliver Lopez <https://github.com/lopezvoliver>`_.

xarray/core/alignment.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@ def override_indexes(self) -> None:
467467
if obj_idx is not None:
468468
for name, var in self.aligned_index_vars[key].items():
469469
new_indexes[name] = aligned_idx
470-
new_variables[name] = var
470+
new_variables[name] = var.copy()
471471

472472
objects[i + 1] = obj._overwrite_indexes(new_indexes, new_variables)
473473

@@ -507,7 +507,7 @@ def _get_indexes_and_vars(
507507
if obj_idx is not None:
508508
for name, var in index_vars.items():
509509
new_indexes[name] = aligned_idx
510-
new_variables[name] = var
510+
new_variables[name] = var.copy()
511511

512512
return new_indexes, new_variables
513513

xarray/tests/test_dataset.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2333,6 +2333,20 @@ def test_align_str_dtype(self) -> None:
23332333
assert_identical(expected_b, actual_b)
23342334
assert expected_b.x.dtype == actual_b.x.dtype
23352335

2336+
@pytest.mark.parametrize("join", ["left", "override"])
2337+
def test_align_index_var_attrs(self, join) -> None:
2338+
# regression test https://github.com/pydata/xarray/issues/6852
2339+
# aligning two objects should have no side effect on their index variable
2340+
# metadata.
2341+
2342+
ds = Dataset(coords={"x": ("x", [1, 2, 3], {"units": "m"})})
2343+
ds_noattr = Dataset(coords={"x": ("x", [1, 2, 3])})
2344+
2345+
xr.align(ds_noattr, ds, join=join)
2346+
2347+
assert ds.x.attrs == {"units": "m"}
2348+
assert ds_noattr.x.attrs == {}
2349+
23362350
def test_broadcast(self) -> None:
23372351
ds = Dataset(
23382352
{"foo": 0, "bar": ("x", [1]), "baz": ("y", [2, 3])}, {"c": ("x", [4])}

0 commit comments

Comments
 (0)