[Numpy-discussion] str == int puzzlement
Sat Jul 31 03:05:27 CDT 2010
2010/7/29 Keith Goodman <email@example.com>:
> On Wed, Jul 28, 2010 at 6:42 PM, Matthew Brett <firstname.lastname@example.org> wrote:
>> Please forgive me if this is obvious, but this surprised me:
>> In : x = np.array(['a', 'b'])
>> In : x == 'a' # this was what I expected
>> Out: array([ True, False], dtype=bool)
>> In : x == 1 # this was strange to me
>> Out: False
> Here's a related case:
>>> np.array(['a', 'b']) == np.array([1, 2])
Yeah, it's just that numpy knows that it cannot compare pears with apples:
>>> a = numpy.asarray(['a', 'b'])
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])
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.
More information about the NumPy-Discussion