(Aside: my question is equally applicable to numpy
structured arrays and non-structured arrays.)
Suppose I have a numpy structured array with the dtype
:
EXAMPLE_DTYPE = np.dtype([("alpha", np.str_), ("beta", np.int64)])
I have a wrapper around the numpy
data array of this dtype
, and then I want to implement a special __getitem__
for it:
class ExampleArray:
data: np.ndarray = np.array([("hello", 0), ("world", 1)], dtype=EXAMPLE_DTYPE)
def __getitem__(self, index: int|str) -> SpecializedArray:
return SpecializedArray(index, self.data[index])
SpecializedArray
is a class which keeps track of the indices used to specialize from a parent array into a derived array:
class SpecializedArray:
specialization: int|str
data: np.ndarray
def __init__(self, specialization: int|str, data: np.ndarray) -> None:
self.specialization = specialization
self.data = data
def __repr__(self) -> str:
return f"{self.specialization} -> {self.data}"
I would like SpecializedArray
to ideally have a “reference” to the parent array it was derived from. What is the best way to provide such a reference? Should I provide the parent by slicing it, since slicing creates a view?
# method in ExampleArray
def __getitem__(self, index: int|str) -> SpecializedArray:
# suppose that SpecializedArray took the parent as a third argument
return SpecializedArray(index, self.data[index], self.data[:])