From a7b29d22edf6ecd6beb938f367be244852bfbb1b Mon Sep 17 00:00:00 2001 From: LTLA Date: Mon, 29 Jan 2024 09:34:59 -0800 Subject: [PATCH] Added a copy method for SparseNdarrays. --- src/delayedarray/SparseNdarray.py | 25 +++++++++++++++++++++++++ tests/test_SparseNdarray.py | 4 ++++ 2 files changed, 29 insertions(+) diff --git a/src/delayedarray/SparseNdarray.py b/src/delayedarray/SparseNdarray.py index 45a9024..786e6a1 100644 --- a/src/delayedarray/SparseNdarray.py +++ b/src/delayedarray/SparseNdarray.py @@ -2,6 +2,7 @@ from typing import Callable, List, Optional, Sequence, Tuple, Union from collections import namedtuple import numpy +import copy from ._isometric import translate_ufunc_to_op_simple, translate_ufunc_to_op_with_args, ISOMETRIC_OP_WITH_ARGS, _choose_operator, _infer_along_with_args from ._subset import _spawn_indices, _getitem_subset_preserves_dimensions, _getitem_subset_discards_dimensions, _repr_subset @@ -777,6 +778,30 @@ def T(self) -> "SparseNdarray": return _transpose_SparseNdarray(self, axes) + # Other stuff + def __copy__(self) -> "SparseNdarray": + """ + Returns: + A deep copy of this object. + """ + return SparseNdarray( + shape=self._shape, + contents=copy.deepcopy(self._contents), + index_dtype=self._index_dtype, + dtype=self._dtype, + is_masked=self._is_masked, + check=False + ) + + + def copy(self) -> "SparseNdarray": + """ + Returns: + A deep copy of this object. + """ + return self.__copy__() + + ######################################################### ######################################################### diff --git a/tests/test_SparseNdarray.py b/tests/test_SparseNdarray.py index d1cb53a..4411977 100644 --- a/tests/test_SparseNdarray.py +++ b/tests/test_SparseNdarray.py @@ -126,6 +126,10 @@ def test_SparseNdarray_check(mask_rate): assert delayedarray.is_masked(y) == (mask_rate > 0) assert delayedarray.is_masked(y) == y.is_masked + clone = copy.copy(y) + clone.contents[0] = "FOOBAR" + assert y.contents[0] != "FOOBAR" + with pytest.raises(ValueError, match="match the extent"): y = delayedarray.SparseNdarray((10, 15, 1), contents)