Skip to content

Commit 4aa7622

Browse files
authored
Use deepcopy recursively on numpy arrays (#4379)
Closes #4362
1 parent ce15385 commit 4aa7622

File tree

3 files changed

+19
-8
lines changed

3 files changed

+19
-8
lines changed

xarray/core/variable.py

+7-8
Original file line numberDiff line numberDiff line change
@@ -932,14 +932,13 @@ def copy(self, deep=True, data=None):
932932
# don't share caching between copies
933933
data = indexing.MemoryCachedArray(data.array)
934934

935-
if deep:
936-
if hasattr(data, "__array_function__") or isinstance(
937-
data, dask_array_type
938-
):
939-
data = data.copy()
940-
elif not isinstance(data, PandasIndexAdapter):
941-
# pandas.Index is immutable
942-
data = np.array(data)
935+
if deep and (
936+
hasattr(data, "__array_function__")
937+
or isinstance(data, dask_array_type)
938+
or (not IS_NEP18_ACTIVE and isinstance(data, np.ndarray))
939+
):
940+
data = copy.deepcopy(data)
941+
943942
else:
944943
data = as_compatible_data(data)
945944
if self.shape != data.shape:

xarray/tests/test_dataarray.py

+6
Original file line numberDiff line numberDiff line change
@@ -6833,3 +6833,9 @@ def test_delete_coords():
68336833
assert a1.dims == ("y", "x")
68346834
assert set(a0.coords.keys()) == {"x", "y"}
68356835
assert set(a1.coords.keys()) == {"x"}
6836+
6837+
6838+
def test_deepcopy_obj_array():
6839+
x0 = DataArray(np.array([object()]))
6840+
x1 = deepcopy(x0)
6841+
assert x0.values[0] is not x1.values[0]

xarray/tests/test_dataset.py

+6
Original file line numberDiff line numberDiff line change
@@ -6454,3 +6454,9 @@ def test_weakref():
64546454
ds = Dataset()
64556455
r = ref(ds)
64566456
assert r() is ds
6457+
6458+
6459+
def test_deepcopy_obj_array():
6460+
x0 = Dataset(dict(foo=DataArray(np.array([object()]))))
6461+
x1 = deepcopy(x0)
6462+
assert x0["foo"].values[0] is not x1["foo"].values[0]

0 commit comments

Comments
 (0)