[Numpy-discussion] ndarray subclassing bug?

Christoph T. Weidemann ctw at cogsci.info
Sun Aug 10 14:48:25 EDT 2008


You wrote:
> numpy functions will return arrays of the type which has the largest priority,
> with ndarrays a priority of 1 by default. If you set a Class variable
> __array_priority__ to a number larger than 1, that should fix your problem.

The following code produces the same behavior:

import numpy as np
class TestArray(np.ndarray):
    __array_priority__=2
    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 sort(self,*args,**kwargs):
        print type(self)
        print type(self.base)


Am I doing something wrong?








> 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 sort(self,*args,**kwargs):
>        print type(self)
>        print type(self.base)
>
>
> Now consider this:
> In [1]: tst = TestArray(np.random.rand(2,3))
>
> In [2]: tst.sort()
> <class '__main__.TestArray'>
> <type 'numpy.ndarray'>
>
> In [3]: np.sort(tst)
> <class '__main__.TestArray'>
> <type 'NoneType'>
> Out[3]:
> TestArray([[ 0.90489484,  0.950291  ,  0.80753772],
>       [ 0.49020689,  0.84582283,  0.61532922]])
>
>
> Why whould tst.sort() show the correct base class and np.sort show
> NoneType as base class for tst?
> I'd appreciate any insights ...
>



More information about the NumPy-Discussion mailing list