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
NotImplementedyou indicate that you do not know if__ne__should returnTrueorFalse.Normally, Python will then swap the operands; if
a != bresults inNotImplemented, it’ll tryb != ainstead. 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_richcompareC function for details.You’ll have to raise
TypeError()manually if that is your expected outcome.