[Numpy-discussion] str == int puzzlement

Friedrich Romstedt friedrichromstedt@gmail....
Sat Jul 31 03:05:27 CDT 2010


2010/7/29 Keith Goodman <kwgoodman@gmail.com>:
> On Wed, Jul 28, 2010 at 6:42 PM, Matthew Brett <matthew.brett@gmail.com> wrote:
>> Hi,
>>
>> Please forgive me if this is obvious, but this surprised me:
>>
>> In [15]: x = np.array(['a', 'b'])
>>
>> In [16]: x == 'a'  # this was what I expected
>> Out[16]: array([ True, False], dtype=bool)
>>
>> In [17]: x == 1 # this was strange to me
>> Out[17]: False
>
> Here's a related case:
>
>>> np.array(['a', 'b']) == np.array([1, 2])
>   False

Yeah, it's just that numpy knows that it cannot compare pears with apples:

>>> a = numpy.asarray(['a', 'b'])
>>> a.__eq__(1)
NotImplemented

so Python falls back to the Python string's or int's __eq__, which
does not know of the structure of numpy, and returns simply False.

In case of the numpy.object array, it's of course forwarded to the
constituents, resulting in the "correct wrong" result (correct because
it's Python-correct, wrong because it's comparing strings to ints).

About Keith's case:

>>> b = numpy.asarray([1, 2])
>>> a.__eq__(b)
NotImplemented
>>> b.__eq__(a)
NotImplemented

So Python falls back to comparing the IDs id(a) == id(b), which also
results in False.

Maybe it would be better to raise a ValueError, which is not caught by
the evaluation mechanism, to prevent such stuff.

Friedrich


More information about the NumPy-Discussion mailing list