Repository: pydata/xarray

Issue:
Don't emit a warning with `.rename` if it is a no-op
### What is your issue?

When running this code:

``` python
import xarray as xr
ds = xr.tutorial.load_dataset("rasm")
ds.rename({"time": "time"})
```

I will get the following warning:
``` python-traceback
UserWarning: rename 'time' to 'time' does not create an index anymore. Try using swap_dims instead or use set_index after rename to create an indexed coordinate.
  ds.rename({"time": "time"})
``` 

Discussion:
welcome[bot]: Thank you for opening this pull request! It may take us a few days to respond here, so thank you for being patient.
If you have questions, some answers may be found in our [contributing guidelines](http://docs.xarray.dev/en/stable/contributing.html).

max-sixty: Thanks @Hoxbro !

Patch:
diff --git a/doc/whats-new.rst b/doc/whats-new.rst
index fb1c07f0..c15bbd4b 100644
--- a/doc/whats-new.rst
+++ b/doc/whats-new.rst
@@ -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
diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py
index ef27071e..bf0daf3c 100644
--- a/xarray/core/dataset.py
+++ b/xarray/core/dataset.py
@@ -4167,6 +4167,9 @@ class Dataset(
             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,):


Test patch:
diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py
index 63175f2b..d497cd5a 100644
--- a/xarray/tests/test_dataarray.py
+++ b/xarray/tests/test_dataarray.py
@@ -1883,6 +1883,16 @@ class TestDataArray:
         ):
             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)]
diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py
index ac641c4a..08bfecca 100644
--- a/xarray/tests/test_dataset.py
+++ b/xarray/tests/test_dataset.py
@@ -3032,8 +3032,7 @@ class TestDataset:
     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:
@@ -3103,6 +3102,15 @@ class TestDataset:
         ):
             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")