Note that Python expects __bool__() to return a bool, otherwise, it throws a TypeError exception (TypeError: __bool__ should return bool, returned …).
__len__() is tried if __bool__() is missing
If an object does not have a __bool__() method, but does have a __len__() method, the returned value determines the Truthness of an object. If the returned value is 0, the object is False, otherwise, it is True.
#!/usr/bin/python3
class with_len:
def __init__(self, cntTrue):
self.cntTrue = cntTrue
def __len__(self):
print("__len__: cntTrue = " + str(self.cntTrue))
self.cntTrue -= 1
return self.cntTrue
L = with_len(4)
while L:
print("Still in loop")
print("Loop exited")