Why does __ne__ exist?

Chris Angelico rosuav at gmail.com
Sun Jan 7 14:48:10 EST 2018


When you create a Python class, you can create dunder methods to
define how your objects respond to the standard operators. With
comparison operators, Python will happily switch the operands around
to find a method to call:

>>> class Spam():
...     def __lt__(self, other):
...         print("%s is less than %s" % (self, other))
...         return True
...
>>> Spam() < 2
<__main__.Spam object at 0x7fb7557b1fd0> is less than 2
True
>>> 3 > Spam()
<__main__.Spam object at 0x7fb7557b1fd0> is less than 3
True
>>> 4 > Spam() < 5
<__main__.Spam object at 0x7fb7557b1fd0> is less than 4
<__main__.Spam object at 0x7fb7557b1fd0> is less than 5
True

But Python will not automatically assume the converse:

>>> Spam() >= 6
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>=' not supported between instances of 'Spam' and 'int'
>>> Spam() > 7
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'Spam' and 'int'

This is good. This is correct. For inequalities, you can't assume that
>= is the exact opposite of < (for example, sets don't behave like
numbers, so "x <= y" is very different from )



More information about the Python-list mailing list