[Numpy-discussion] Behaviour of ndarray and other objects with __radd__?

Jonathan Taylor jonathan.taylor@utoronto...
Wed Jun 15 10:12:52 CDT 2011


Hi,

I would like to have objects that I can mix with ndarrays in
arithmetic expressions but I need my object to have control of the
operation even when it is on the right hand side of the equation.  I
realize from the documentation that the way to do this is to actually
subclass ndarray but this is undesirable because I do not need all the
heavy machinery of a ndarray and I do not want users to see all of the
ndarray methods.  Is there a way to somehow achieve these goals?

I would also very much appreciate some clarification of what is
happening in the following basic example:

import numpy as np
class Foo(object):
    # THE NEXT LINE IS COMMENTED
    # __array_priority__ = 0
    def __add__(self, other):
        print 'Foo has control over', other
        return 1
    def __radd__(self, other):
        print 'Foo has control over', other
        return 1

x = np.arange(3)
f = Foo()

print f + x
print x + f

yields

Foo has control over [0 1 2]
1
Foo has control over 0
Foo has control over 1
Foo has control over 2
[1 1 1]

I see that I have control from the left side as expected and I suspect
that what is happening in the second case is that numpy is trying to
"broadcast" my object onto the left side as if it was an object array?

Now if I uncomment the line __array_priority__ = 0 I do seem to
accomplish my goals (see below) but I am not sure why.  I am
surprised, given what I have read in the documentation, that
__array_priority__ does anything in a non subclass of ndarray.
Furthermore, I am even more surprised that it does anything when it is
0, which is the same as ndarray.__array_priority__ from what I
understand.  Any clarification of this would be greatly appreciated.

Output with __array_priority__ uncommented:

jtaylor@yukon:~$ python foo.py
Foo has control over [0 1 2]
1
Foo has control over [0 1 2]
1

Thanks,
Jonathan.


More information about the NumPy-Discussion mailing list