Avoid numpy distributing an operation for overloaded operator

Viewed 329

By default, numpy distributes operations across arrays if it doesn't know the type of the other object. This works well in most cases. For example, the following behaves as expected.

np.arange(5) + 5 # = [5, 6, 7, 8, 9]

I would like to define a class that overrides the addition operator as illustrated in the code below.

class Example:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        return other + self.value

    def __radd__(self, other):
        return other + self.value

It works well for scalar values. For example,

np.arange(5) + Example(5) # = [5, 6, 7, 8, 9]

However, it doesn't quite do what I want for vector values. For example,

np.arange(5) + Example(np.arange(5)) 

yields the output

array([array([0, 1, 2, 3, 4]), array([1, 2, 3, 4, 5]),
   array([2, 3, 4, 5, 6]), array([3, 4, 5, 6, 7]),
   array([4, 5, 6, 7, 8])], dtype=object)

because the __add__ operator of the preceding numpy array takes priority over the __radd__ operator that I have defined. Numpy's __add__ operator calls __radd__ for each element of the numpy array yielding an array of arrays. How can I avoid numpy distributing the operation? I would like to avoid subclassing numpy arrays.

1 Answers
Related