0

(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[:])
8
  • Why not just self.data? Why the slice? Commented Jun 18, 2024 at 22:43
  • @user2357112 I'm not sure whether a copy will unnecessarily be made, while the slicing forces a view to be created? Commented Jun 18, 2024 at 22:48
  • 1
    It won't create a copy. Even if Python did work in a way where that would create a copy, making a view wouldn't help - those same (nonexistent) mechanics would just copy the view. Commented Jun 18, 2024 at 22:50
  • @user2357112 I guess I am never sure when Python just passes a reference to an object, versus creating a deepcopy. Commented Jun 18, 2024 at 23:05
  • 1
    Python almost never copies anything you don't explicitly copy. Commented Jun 18, 2024 at 23:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.