Skip to content

Fix aligned index variable metadata side effect #6857

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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