Search code examples
pythonpython-3.xcomparison-operators

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?


Solution

  • 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.