1
votes

Someone asks the question here: Subclassing numpy ndarray problem but it is basically unanswered.

Here is my version of the question. Suppose you subclass the numpy.ndarray to something that automatically expands when you try to set an element beyond the current shape. You would need to override the setitem and use some numpy.concatenate calls to construct a new array and then assign it to "self" somehow. How to assign the array to "self"?

class myArray(numpy.ndarray):
    def __new__(cls, input_array):
        obj = numpy.asarray(input_array).view(cls)
        return(obj)

    def __array_finalize__(self, obj):
        if obj is None: return

    try:
        super(myArray, self).__setitem__(coords, value)
    except IndexError as e:
        logging.error("Adjusting array")
        ...
        self = new_array # THIS IS WRONG
1
That assignment to self seems just nonsense, how are you suppsoed to replace an object? Besides, doing such with a numpy array would invalidate views of the array. You just can't do this with a subclass, there is a reason ndarray.resize is so restrictive... - seberg

1 Answers

3
votes

Why subclass? Why not just give your wrapper object it's own data member that is an ndarray and use __getitem__ and __setitem__ to operate on the wrapped data member? This is basically what ndarray already does, wrapping Python's built-in containers. Also have a look at Python Pandas which already does a lot of what you're talking about wrapped on top of ndarray.