Storing a numpy ndarray subclass as return value during conversion. Is it safe to set __array_priority__?

I am trying to subclass numpy ndarrayand am lucky. The behavior I would like is almost exactly the same as the example specified in the documentation. I want to add a parameter nameto an array (which I use to track where the data came from).

class Template(np.ndarray):
    """A subclass of numpy n dimensional array that allows for a
    reference back to the name of the template it came from.
    """
    def __new__(cls, input_array, name=None):
        obj = np.asarray(input_array).view(cls)
        obj.name = name
        return obj

    def __array_finalize__(self, obj):
        if obj is None: return
        self.name = getattr(obj, 'name', None)

This works, except that, like this question , I want any conversion involving my subclass to return another instance of my subclass .

Sometimes numpy functions return an instance Template:

>>> a = Template(np.array([[1,2,3], [2,4,6]], name='from here')
>>> np.dot(a, np.array([[1,0,0],[0,1,0],[0,0,1]]))
Template([[1, 2, 3],
       [2, 4, 6]])

However, sometimes they do not:

>>> np.dot(np.array([[1,0],[0,1]]), a)
array([[1, 2, 3],
       [2, 4, 6]])

, , , OP __wrap_array__ . . __array_wrap__. , , , , __array_wrap__ - __array_priority__ :

, ufunc (np.add) __array_wrap__ __array_priority__

, . -: __array_priority__ , __array_wrap__ ? : / ?

+5
1

__array_priority __:

>>> np.array([[1,0],[0,1]]).__array_priority__
0.0
>>> a.__array_priority__
0.0

, /. ( __array_wrap __)

, , ( ) .

, __array_priority__.

class Template(np.ndarray):
    __array_priority__ = 1.0 (Or whichever value is high enough)
    ...

, . , .

0

All Articles