Why does __ne__ exist?

Thomas Jollans tjol at tjol.eu
Sun Jan 7 15:13:25 EST 2018


On 07/01/18 20:55, Chris Angelico wrote:
> Under what circumstances would you want "x != y" to be different from
> "not (x == y)" ?

In numpy, __eq__ and __ne__ do not, in general, return bools.

Python 3.6.3 (default, Oct  3 2017, 21:45:48)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> a = np.array([1,2,3,4])
>>> b = np.array([0,2,0,4])
>>> a == b
array([False,  True, False,  True], dtype=bool)
>>> a != b
array([ True, False,  True, False], dtype=bool)
>>> not (a == b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()
>>> ~(a == b)
array([ True, False,  True, False], dtype=bool)
>>>

I couldn't tell you why this was originally allowed, but it does turn
out to be strangely useful. (As far as the numpy API is concerned, it
would be even nicer if 'not' could be overridden, IMHO)

Cheers
Thomas



More information about the Python-list mailing list