[Numpy-discussion] __array_priority__ don't work for gt, lt, ... operator

Thomas Robitaille thomas.robitaille at gmail.com
Sun May 12 03:59:22 EDT 2013

I've also been having issues with __array_priority__ - the following
code behaves differently for __mul__ and __rmul__:

import numpy as np

class TestClass(object):

    def __init__(self, input_array):
        self.array = input_array

    def __mul__(self, other):
        print "Called __mul__"

    def __rmul__(self, other):
        print "Called __rmul__"

    def __array_wrap__(self, out_arr, context=None):
        print "Called __array_wrap__"
        return TestClass(out_arr)

    def __array__(self):
        print "Called __array__"
        return np.array(self.array)

with output:

In [7]: a = TestClass([1,2,3])

In [8]: print type(np.array([1,2,3]) * a)
Called __array__
Called __array_wrap__
<class '__main__.TestClass'>

In [9]: print type(a * np.array([1,2,3]))
Called __mul__
<type 'NoneType'>

Is this also an oversight? I opened a ticket for it a little while ago:


Any ideas?


On 10 May 2013 18:34, Charles R Harris <charlesr.harris at gmail.com> wrote:
> On Fri, May 10, 2013 at 10:08 AM, Frédéric Bastien <nouiz at nouiz.org> wrote:
>> Hi,
>> it popped again on the Theano mailing list that this don't work:
>> np.arange(10) <= a_theano_vector.
>> The reason is that __array_priority__ isn't respected for that class of
>> operation.
>> This page explain the problem and give a work around:
>> http://stackoverflow.com/questions/14619449/how-can-i-override-comparisons-between-numpys-ndarray-and-my-type
>> The work around is to make a python function that will decide witch
>> version of the comparator to call and do the call. Then we tell NumPy to use
>> that function instead of its current function with: np.set_numeric_ops(...)
>> But if we do that, when we import theano, we will slow down all normal
>> numpy comparison for the user, as when <= is execute, first there will be
>> numpy c code executed, that will call the python function to decide witch
>> version to do, then if it is 2 numpy ndarray, it will call again numpy c
>> code.
>> That isn't a good solution. We could do the same override in C, but then
>> theano work the same when there isn't a c++ compiler. That isn't nice.
>> What do you think of changing them to check for __array_priority__ before
>> doing the comparison?
> This looks like an oversight and should be fixed.
> Chuck
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion

More information about the NumPy-Discussion mailing list