The documentation clearly states that
When this method (
__bool__
) is not defined,__len__()
is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither__len__()
nor__bool__()
, all its instances are considered true.
Bold is my insertion, italics is mine but the text is actually there. The fact that the class must contain the method is readily tested by
class A:
pass
a = A()
a.__bool__ = (lamda self: False).__get__(a, type(a))
print(bool(A()), bool(a))
The result is True True
, as the documentation claims. Overriding __len__
yields the same result:
b = A()
b.__len__ = (lambda self: 0).__get__(b, type(b))
print(bool(A()), bool(b))
This works exactly as the documentation claims it will. However, I find the reasoning behind this to be a little counter-intuitive. I understand that the bool
builtin does not look at the methods of the instance, but I do not understand why. Does someone with a knowledge of the internal workings know why only the class-level __bool__
and __len__
methods affect truthiness while instance-level methods are ignored?