Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does NotImplemented evaluate to True?

Tags:

python

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?

like image 639
Remco Haszing Avatar asked Apr 30 '14 21:04

Remco Haszing


1 Answers

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.

like image 175
Martijn Pieters Avatar answered Nov 14 '22 06:11

Martijn Pieters