diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index b8e7bf9b73f..952e10c6127 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -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 diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index 708e62630ec..5d18d5e12d5 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -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) @@ -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)