Skip to content

Commit

Permalink
Use ._replace for half the method
Browse files Browse the repository at this point in the history
  • Loading branch information
max-sixty committed Oct 8, 2023
1 parent 40ffa5c commit 1252364
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
7 changes: 4 additions & 3 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -10344,12 +10344,13 @@ def drop_attrs(self) -> Self:
Removes all attributes from the Dataset and its variables.
"""
# Remove attributes from the dataset
self = self.copy()

self.attrs = {}
self = self._replace(attrs={})

# Remove attributes from each variable in the dataset
for var in self.variables:
# variables don't have a `._replace` method, so we copy and then remove. If
# we added a `._replace` method, we could use that instead.
self[var] = self[var].copy()
self[var].attrs = {}

return self
4 changes: 3 additions & 1 deletion xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -4369,7 +4369,7 @@ def test_drop_attrs(self) -> None:
# Example with variables and coords with attrs, check they're dropped too
var = Variable("x", [1, 2, 3], attrs=dict(x=1, y=2))
idx = IndexVariable("y", [1, 2, 3], attrs=dict(c=1, d=2))
ds = Dataset(dict(x=var), coords=dict(y=idx)).assign_attrs(a=1, b=2)
ds = Dataset(dict(var1=var), coords=dict(y=idx)).assign_attrs(a=1, b=2)
assert ds.coords["y"].attrs != {}

original = ds.copy(deep=True)
Expand All @@ -4378,6 +4378,8 @@ def test_drop_attrs(self) -> None:
assert result.attrs == {}
assert result["x"].attrs == {}
assert result["y"].attrs == {}
assert list(result.data_vars) == list(ds.data_vars)
assert list(result.coords) == list(ds.coords)

# Doesn't change original
assert_identical(ds, original)
Expand Down

0 comments on commit 1252364

Please sign in to comment.