[Numpy-discussion] Scalar-ndarray arguments passed to not_equal
Keith Goodman
kwgoodman@gmail....
Thu Feb 11 10:56:48 CST 2010
On Thu, Feb 11, 2010 at 7:27 AM, Friedrich Romstedt
<friedrichromstedt@gmail.com> wrote:
> Keith Goodman:
>> No one answered my post either :(
>>
>> http://old.nabble.com/arrays-and-__eq__-td26987903.html#a26987903
>>
>> Is it the same issue?
>
> First, before I post the package on github, I dived into Keith's
> problem, and here comes the explanation to the wreid behaviour:
>
> I used the code:
>
> class myclass(object):
> def __init__(self, arr):
> self.arr = arr
> def __eq__(self, other):
> print "Instance", id(self), "testing with", other, "..."
> print "type =", type(other)
> if numpy.isscalar(other) or isinstance(other, numpy.ndarray):
> x = myclass(self.arr.copy())
> x.arr = x.arr == other
> else:
> raise TypeError()
> return x
>
> Then, the session is:
>
>>>> m = myclass([1, 2, 3])
>>>> a = numpy.asarray([9, 2, 3])
>>>> (m == a).arr
> Instance 12345 testing with [9, 2, 3] ...
> type = <type 'numpy.ndarray'>
> array([False, True, True], dtype = bool)
>
> So far, everything ok. And now, to something completely different ...
>
>>>> a == m
> Instance 12345 testing with 9 ...
> type = <type 'int'>
> Instance 12345 testing with 2 ...
> type = <type 'int'>
> Instance 12345 testing with 3 ...
> type = <type 'int'>
>
> So, the "a" applies the "m" to each of its elements. This is the
> Numpy behaviour, because "m" seems scalar to Numpy. The result is a
> myclass instance for each element. But it doesn't matter what this
> myclass result instance holds, because Numpy uses Python's truth
> interpretation to yield the elements of the call to (a == m). This
> yields True for each element, because only False, None, 0, and 0.0 are
> False in Python. As there is no truth testing operator in "class
> myclass", this is the only option for Numpy. So no bug, only features
> ...
I tried adding truth testing but they are never called:
def truth(self, other):
print 'TRUTH'
def is_(self, other):
print 'IS_'
Is there some way to tell numpy to use my __eq__ instead of its own?
That would solve my problem. I had a similar problem with __radd__
which was solved by setting __array_priority__ = 10. But that doesn't
work in this case.
I wish I knew enough to reply to your post. Then I could return the
favor. You'll have to settle for a thank you. Thank you.
More information about the NumPy-Discussion
mailing list