FalseAdvanced Examples

Boolean literal representing false/0

Custom falsy objects

Making your own objects evaluate to False.

python
class EmptyContainer:
    def __init__(self):
        self.items = []
    def __bool__(self):
        return len(self.items) > 0
    def __repr__(self):
        return f"EmptyContainer({self.items})"

c = EmptyContainer()
print(f"{c} is {'truthy' if c else 'falsy'}")
c.items.append(1)
print(f"{c} is {'truthy' if c else 'falsy'}")

Implementing __bool__ lets you control how your objects behave in boolean contexts.

Want to try these examples interactively?

Open Advanced Playground