Subclassing the numpy array, where all form change operations return a normal array

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) # Do a bunch of class dependant initialization and attribute copying. # ... return out else: return np.asarray(out_arr) A = np.arange(10) A.shape = (5, 2) A = arr.view(NewArrayClass) # Would like this to be np.ndarray, but get new_array_class. print type(np.sum(A, 0)) 

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.

+7
source share
1 answer

If you do not introduce new members into your NewArrayClass instances, you can reassign the __class__ attribute of the returned instances.

 A.__class__ = np.ndarray 

That is why you would like to do that. Do you have stringent type checks elsewhere? You would go much more with a duck set.

+1
source

All Articles