[Numpy-discussion] ndarray subclassing

Travis E. Oliphant oliphant@enthought....
Wed Apr 30 23:45:02 CDT 2008


ctw wrote:
> Hi!
>
> I ran into some strange (at least to me) issues with sublasses of
> ndarray. The following minimal class definition illustrates the
> problem:
>
> ====================================================
>
> import numpy as np
> class TestArray(np.ndarray):
>     def __new__(cls, data, info=None, dtype=None, copy=False):
>         subarr = np.array(data, dtype=dtype, copy=copy)
>         subarr = subarr.view(cls)
>         return subarr
>
>     def __array_finalize__(self,obj):
>         print "self: ",self.shape
>         print "obj: ",obj.shape
>
> =====================================================
>
> When I run this code interactively with IPython and then generate
> TestArray instances, __array_finalize__ seems to get called when
> printing out arrays with more than 1 dimension and self.shape seems to
> drop a dimension. Everything works fine if the array has just 1
> dimension:
>
> In [3]: x = TestArray(np.arange(5))
> self:  (5,)
> obj:  (5,)
>
> In [4]: x
> Out[4]: TestArray([0, 1, 2, 3, 4])
>
> This is all expected behavior.
> However things change when the array is 2-D:
>
> In [5]: x = TestArray(np.zeros((2,3)))
> self:  (2, 3)
> obj:  (2, 3)
>
> In [6]: x
> Out[6]: self:  (3,)
> obj:  (2, 3)
> self:  (3,)
> obj:  (2, 3)
>
> TestArray([[ 0.,  0.,  0.],
>        [ 0.,  0.,  0.]])
>   

You are just seeing the result of __repr__.   The printing code works by 
accessing slices of the array.  These slices create new instances of 
your TestArray class which have a smaller number of dimensions.  That's all.

Is the printing code causing you other kinds of problems?

-Travis



More information about the Numpy-discussion mailing list