From 4aa7622b6ff16647df64fe69f39438b7cbe9576c Mon Sep 17 00:00:00 2001 From: darikg Date: Thu, 27 Aug 2020 10:56:48 -0400 Subject: [PATCH] Use deepcopy recursively on numpy arrays (#4379) Closes #4362 --- xarray/core/variable.py | 15 +++++++-------- xarray/tests/test_dataarray.py | 6 ++++++ xarray/tests/test_dataset.py | 6 ++++++ 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/xarray/core/variable.py b/xarray/core/variable.py index 7c398066830..39d663410ec 100644 --- a/xarray/core/variable.py +++ b/xarray/core/variable.py @@ -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: diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py index 842b8962352..9c08ad5d8fd 100644 --- a/xarray/tests/test_dataarray.py +++ b/xarray/tests/test_dataarray.py @@ -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] diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index 9ac3af90a17..2d37dc670b6 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -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]