Skip to content

Commit

Permalink
Use deepcopy recursively on numpy arrays (#4379)
Browse files Browse the repository at this point in the history
Closes #4362
  • Loading branch information
darikg committed Aug 27, 2020
1 parent ce15385 commit 4aa7622
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 8 deletions.
15 changes: 7 additions & 8 deletions xarray/core/variable.py
Expand Up @@ -932,14 +932,13 @@ def copy(self, deep=True, data=None):
# don't share caching between copies
data = indexing.MemoryCachedArray(data.array)

if deep:
if hasattr(data, "__array_function__") or isinstance(
data, dask_array_type
):
data = data.copy()
elif not isinstance(data, PandasIndexAdapter):
# pandas.Index is immutable
data = np.array(data)
if deep and (
hasattr(data, "__array_function__")
or isinstance(data, dask_array_type)
or (not IS_NEP18_ACTIVE and isinstance(data, np.ndarray))
):
data = copy.deepcopy(data)

else:
data = as_compatible_data(data)
if self.shape != data.shape:
Expand Down
6 changes: 6 additions & 0 deletions xarray/tests/test_dataarray.py
Expand Up @@ -6833,3 +6833,9 @@ def test_delete_coords():
assert a1.dims == ("y", "x")
assert set(a0.coords.keys()) == {"x", "y"}
assert set(a1.coords.keys()) == {"x"}


def test_deepcopy_obj_array():
x0 = DataArray(np.array([object()]))
x1 = deepcopy(x0)
assert x0.values[0] is not x1.values[0]
6 changes: 6 additions & 0 deletions xarray/tests/test_dataset.py
Expand Up @@ -6454,3 +6454,9 @@ def test_weakref():
ds = Dataset()
r = ref(ds)
assert r() is ds


def test_deepcopy_obj_array():
x0 = Dataset(dict(foo=DataArray(np.array([object()]))))
x1 = deepcopy(x0)
assert x0["foo"].values[0] is not x1["foo"].values[0]

0 comments on commit 4aa7622

Please sign in to comment.