Skip to content

Commit

Permalink
Don't raise rename warning if it is a no operation (pydata#8266)
Browse files Browse the repository at this point in the history
* Don't raise rename warning if it is a no operation

* xr.Dataset -> Dataset

* Remove pytest.warns

* Add whatsnew
  • Loading branch information
hoxbro authored Oct 4, 2023
1 parent 25c7689 commit e09609c
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ Deprecations

Bug fixes
~~~~~~~~~
- :py:meth:`DataArray.rename` & :py:meth:`Dataset.rename` would emit a warning
when the operation was a no-op. (:issue:`8266`)
By `Simon Hansen <https://github.com/hoxbro>`_.


Documentation
Expand Down
3 changes: 3 additions & 0 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -4167,6 +4167,9 @@ def _rename(
create_dim_coord = False
new_k = name_dict[k]

if k == new_k:
continue # Same name, nothing to do

if k in self.dims and new_k in self._coord_names:
coord_dims = self._variables[name_dict[k]].dims
if coord_dims == (k,):
Expand Down
10 changes: 10 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -1883,6 +1883,16 @@ def test_rename_dimension_coord_warnings(self) -> None:
):
da.rename(x="y")

# No operation should not raise a warning
da = xr.DataArray(
data=np.ones((2, 3)),
dims=["x", "y"],
coords={"x": range(2), "y": range(3), "a": ("x", [3, 4])},
)
with warnings.catch_warnings():
warnings.simplefilter("error")
da.rename(x="x")

def test_init_value(self) -> None:
expected = DataArray(
np.full((3, 4), 3), dims=["x", "y"], coords=[range(3), range(4)]
Expand Down
12 changes: 10 additions & 2 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -3032,8 +3032,7 @@ def test_rename_old_name(self) -> None:
def test_rename_same_name(self) -> None:
data = create_test_data()
newnames = {"var1": "var1", "dim2": "dim2"}
with pytest.warns(UserWarning, match="does not create an index anymore"):
renamed = data.rename(newnames)
renamed = data.rename(newnames)
assert_identical(renamed, data)

def test_rename_dims(self) -> None:
Expand Down Expand Up @@ -3103,6 +3102,15 @@ def test_rename_dimension_coord_warnings(self) -> None:
):
ds.rename(x="y")

# No operation should not raise a warning
ds = Dataset(
data_vars={"data": (("x", "y"), np.ones((2, 3)))},
coords={"x": range(2), "y": range(3), "a": ("x", [3, 4])},
)
with warnings.catch_warnings():
warnings.simplefilter("error")
ds.rename(x="x")

def test_rename_multiindex(self) -> None:
midx = pd.MultiIndex.from_tuples([([1, 2]), ([3, 4])], names=["a", "b"])
midx_coords = Coordinates.from_pandas_multiindex(midx, "x")
Expand Down

0 comments on commit e09609c

Please sign in to comment.