__bool__ — Easy Examples
Called by bool(); defines truthiness of the object
Implementing __bool__
Basic implementation of __bool__ in a class.
python
class NonEmpty: def __init__(self, items): self.items = items def __bool__(self): return len(self.items) > 0 a = NonEmpty([1, 2, 3]) b = NonEmpty([]) print(bool(a)) print(bool(b)) if a: print("a is truthy")
__bool__ called by bool(); defines truthiness of the object. Implementing it lets you customize how Python interacts with your objects.
__bool__ in action
Seeing __bool__ called by Python's built-in operations.
python
# How Python calls __bool__ automatically class Demo: def __init__(self, value): self.value = value def __bool__(self): print(f"__bool__ was called!") return True d = Demo(42) # This triggers __bool__: print(bool(d))
Python automatically calls __bool__ when you use the corresponding operator or function on your object.
Want to try these examples interactively?
Open Easy Playground