Skip to content

Commit

Permalink
Fix aligned index variable metadata side effect (pydata#6857)
Browse files Browse the repository at this point in the history
* 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]>
  • Loading branch information
benbovy and dcherian authored Aug 31, 2022
1 parent 0496cb4 commit 4880012
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ Bug fixes
By `Jimmy Westling <https://github.com/illviljan>`_.
- Fix incompatibility with numpy 1.20 (:issue:`6818`, :pull:`6821`)
By `Michael Niklas <https://github.com/headtr1ck>`_.
- Fix side effects on index coordinate metadata after aligning objects. (:issue:`6852`, :pull:`6857`)
By `Benoît Bovy <https://github.com/benbovy>`_.
- Make FacetGrid.set_titles send kwargs correctly using `handle.udpate(kwargs)`.
(:issue:`6839`, :pull:`6843`)
By `Oliver Lopez <https://github.com/lopezvoliver>`_.
Expand Down
4 changes: 2 additions & 2 deletions xarray/core/alignment.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ def override_indexes(self) -> None:
if obj_idx is not None:
for name, var in self.aligned_index_vars[key].items():
new_indexes[name] = aligned_idx
new_variables[name] = var
new_variables[name] = var.copy()

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

Expand Down Expand Up @@ -507,7 +507,7 @@ def _get_indexes_and_vars(
if obj_idx is not None:
for name, var in index_vars.items():
new_indexes[name] = aligned_idx
new_variables[name] = var
new_variables[name] = var.copy()

return new_indexes, new_variables

Expand Down
14 changes: 14 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -2333,6 +2333,20 @@ def test_align_str_dtype(self) -> None:
assert_identical(expected_b, actual_b)
assert expected_b.x.dtype == actual_b.x.dtype

@pytest.mark.parametrize("join", ["left", "override"])
def test_align_index_var_attrs(self, join) -> None:
# regression test https://github.com/pydata/xarray/issues/6852
# aligning two objects should have no side effect on their index variable
# metadata.

ds = Dataset(coords={"x": ("x", [1, 2, 3], {"units": "m"})})
ds_noattr = Dataset(coords={"x": ("x", [1, 2, 3])})

xr.align(ds_noattr, ds, join=join)

assert ds.x.attrs == {"units": "m"}
assert ds_noattr.x.attrs == {}

def test_broadcast(self) -> None:
ds = Dataset(
{"foo": 0, "bar": ("x", [1]), "baz": ("y", [2, 3])}, {"c": ("x", [4])}
Expand Down

0 comments on commit 4880012

Please sign in to comment.