Implement Truth and Length Protocols
Core idea
bool(x) and conditions use __bool__ if defined; it must return a Boolean. Otherwise Python uses __len__ if available, treating zero as false. If neither exists, ordinary instances are truthy. len(x) calls the length protocol, which requires a nonnegative integer. A custom Boolean policy may differ from length, but document surprising behavior.
class Batch: def __init__(self, items): self.items = items def __len__(self): return len(self.items)for b in [Batch([]), Batch([3, 4])]: print(len(b), bool(b))Length supplies truth when bool is absent.
Explicit readiness policy
class Queue: def __len__(self): return 3 def __bool__(self): return Falseq = Queue()print(len(q), bool(q))The explicit Boolean method has priority. Here the queue is deliberately not ready.
Intentional failure: negative length
class Bad: def __len__(self): return -1print(len(Bad()))Negative length violates the protocol.
Common mistake
__bool__ returning 1 rather than True raises TypeError. In CPython extremely large lengths can also overflow len(); do not rely on implementation-specific limits for truth decisions.
Practice
Implement a basket with len; test empty and nonempty baskets. Add a Boolean method returning a real bool and compare behavior.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Truth and length
Check your understanding of truth and length protocols.
What is printed?
class Box: def __len__(self): return 0print(bool(Box()))What is printed?
class Job: def __bool__(self): return True def __len__(self): return 0j = Job()print(bool(j), len(j))What happens?
class Box: def __bool__(self): return 1print(bool(Box()))If an ordinary class defines neither truth nor length, what is the default?