Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't NotImplemented raise a TypeError?

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?

like image 882
Turion Avatar asked Nov 17 '25 12:11

Turion


1 Answers

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.

like image 84
Martijn Pieters Avatar answered Nov 20 '25 04:11

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!