Suppose I define a class A and I don't want anyone to write an inequality of that class without getting away.
class A():
def __ne__(self, other):
return NotImplemented
print(A() != A())
But this prints out True and doesn't raise a TypeError although I have deliberately "turned off" the != operator?
When you return NotImplemented you indicate that you do not know if __ne__ should return True or False.
Normally, Python will then swap the operands; if a != b results in NotImplemented, it'll try b != a instead. That'll fail here too, since you use the same type on both sides of the operator. For the != operator, Python will then fall back to comparing their memory addresses, and these are not the same (two separate instances), so False is returned.
See the do_richcompare C function for details.
You'll have to raise TypeError() manually if that is your expected outcome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With