Python › Magic Methods & Operator Overloading

How does __bool__ (or the legacy __nonzero__) determine an object's truthiness, and what's the fallback if it's not defined?

Advanced

Answer

__bool__(self) should return True or False and controls how an object behaves in boolean contexts like `if obj:` or `bool(obj)`. If __bool__ isn't defined, Python falls back to __len__, treating the object as False if its length is 0 and True otherwise. If neither is defined, all instances are considered truthy by default.
class Inventory:
    def __init__(self, items):
        self.items = items
    def __bool__(self):
        return len(self.items) > 0

inv = Inventory([])
if not inv:
    print('Inventory is empty')
Real-world example A custom QuerySet-like class defines __bool__ to check whether any results exist without forcing a full evaluation or count of the entire result set, avoiding an expensive count query.

Common follow-ups: What's the evaluation order between __bool__ and __len__?;Why might defining __len__ alone be sufficient?