I recently stumbled upon Python's NotImplemented
builtin. After some reading I do get it's purpose now, but I don't see why it evaluates to True
as a boolean. The following example makes it seem like some kind of cruel joke to me:
>>> class A:
... def __eq__(self, other):
... return NotImplemented
...
>>>
>>> a = A()
>>> a == 1
False
>>> bool(a.__eq__(1))
True
My question is simple: Why does NotImplemented
evaluate to True
?
Because it doesn't evaluate to False
; the default is to consider all objects True
unless they have a length of 0 (containers), or are zero (numeric); see the Truth Value Testing reference.
However, returning NotImplemented
signals to Python that the equality test is not implemented, and the inverse (1).__eq__(a)
is tried instead. If that method doesn't exist either, the objects are not equal if they are not the same object (a is 1
is False
).
In other words, NotImplemented
is a special singleton object, a sentinel to signal to Python that you want Python to try something else, as the equality test between this object and the other is not supported.
As such it was never meant to be used in a boolean context. It is never meant to convey False
.
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