I have a subclass of an array where some additional attributes are only valid for the original form of the object. Is there a way to make sure that all array shape changing operations return a normal numpy array instead of an instance of my class?
I already wrote array_wrap, but that doesn't seem to affect operations like np.mean , np.sum or np.rollaxis . All this just returns an instance of my class.
import numpy as np class NewArrayClass(np.ndarray): __array_priority__ = 3.0 def __array_wrap__(self, out_arr, context=None): if out_arr.shape == self.shape: out = out_arr.view(new_array)
I suppose I need to do something in __new__ or __array_finalize__ , but I don't know what.
Update: After carefully reading the numpy documentation for the subclass ( http://docs.scipy.org/doc/numpy/user/basics.subclassing.html ), all operations of changing the shape of the array perform the operation โnew from the templateโ. So the question is, how to make the "new from template" operation return ndarray instances instead of instances of my class. As far as I can tell, __new__ never called inside these functions.
Alternative: Assuming this is not possible, how do I at least identify in __array_finalize__ new template operation (as opposed to viewing)? This, at least, would allow me to dereference some attributes that are copied by reference. I could also set a flag or something telling the new instance that its form is invalid.
kiyo
source share