True — Advanced Examples
Boolean literal representing true/1
Custom truthy objects
Controlling truthiness via __bool__ and __len__.
python
class QueryResult: def __init__(self, rows): self.rows = rows def __bool__(self): return len(self.rows) > 0 def __len__(self): return len(self.rows) empty = QueryResult([]) full = QueryResult([{"id": 1}, {"id": 2}]) print(f"Empty result: {bool(empty)}") print(f"Full result: {bool(full)}") if full: print(f"Got {len(full)} rows")
Python calls __bool__ first; if not defined, falls back to __len__. If neither exists, the object is always truthy.
Want to try these examples interactively?
Open Advanced Playground