Python Reference ยท Classes and Special Methods
__bool__() and __len__() truthiness
Reference for Python truth value testing: how __bool__() and __len__() decide whether an object is truthy or falsy in if, while, and, or and not.
Every Python object can be used as a condition. if obj:, while obj:, not obj and the and / or operators all ask the object for its truth value. Python decides in this order: it calls __bool__() if the class defines it; otherwise it calls __len__() and treats 0 as false; if neither exists, the object is always true.
That is why empty containers, 0, None and "" are falsy, while your own plain class instances are truthy by default.
class Basket: def __init__(self, items): self.items = items def __len__(self): return len(self.items) print(bool(Basket([])), bool(Basket(["apple"]))) # False True
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
def __bool__(self) -> bool: ... def __len__(self) -> int: ...
| Name | Description |
|---|---|
__bool__(self) |
Must return exactly True or False. Used first for truth testing. |
__len__(self) |
Must return a non-negative integer. Used when __bool__ is missing; 0 means false. |
Return value: bool(obj) returns True or False.
Raises: TypeError if __bool__ returns something that is not a bool, or if __len__ returns a non-integer; ValueError if __len__ returns a negative number.
Usage notes
- Defaults. An object without either method is truthy. Built-in falsy values are
None,False, zero of any numeric type, and empty sequences and collections ("",[],(),{},set(),range(0)). __bool__takes priority. If both exist,__len__is not consulted for truth testing, as the second example shows.- Do not return
1or0from__bool__; it must be a realbool. andandorreturn operands, not booleans."" or "anonymous"gives"anonymous", andx and ygivesxwhenxis falsy. Onlynotalways returns abool.- Pitfall with
None.if obj:is false for an empty collection too. When you mean "is it missing?", writeif obj is None:. - Pitfall with custom
__len__. A container-like class with__len__becomes falsy when empty, which may surprise code that writesif node:to test for existence. - Libraries sometimes forbid it. NumPy arrays with several elements raise
ValueErrorin a boolean context; use.any()or.all(). __nonzero__was the Python 2 name; it is ignored in Python 3.