When trying to evaluate the truthiness of an object x, basically the following is done in order:
x.__bool__()is called. If__bool__is not implemented, thenx.__len__()is called. If__len__()is not implemented, then- return
True. As a result, all user defined objects are truthy unless__bool__or__len__are implemented. Also, we can useif iterablew/o the need to useif len(iterable).
class A:
...
class B:
def __bool__(self):
print("In __bool__")
return False
class C:
def __len__(self):
print("In __len__")
return False
class D:
def __bool__(self):
print("In __bool__")
return False
def __len__(self):
print("In __len__")
return Falseif A(): print("Truthy") #=> "Truthy"
if B(): print("Truthy") #=> "In __bool__"
if C(): print("Truthy") #=> "In __len__"
if D(): print("Truthy") #=> "In __bool__"