Skip to content
Tutorials Center
My learning

Topics

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.

Python
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

Python Truthiness through __len__ and __bool__

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.

Python __bool__ wins over __len__

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

Python
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 1 or 0 from __bool__; it must be a real bool.
  • and and or return operands, not booleans. "" or "anonymous" gives "anonymous", and x and y gives x when x is falsy. Only not always returns a bool.
  • Pitfall with None. if obj: is false for an empty collection too. When you mean "is it missing?", write if obj is None:.
  • Pitfall with custom __len__. A container-like class with __len__ becomes falsy when empty, which may surprise code that writes if node: to test for existence.
  • Libraries sometimes forbid it. NumPy arrays with several elements raise ValueError in a boolean context; use .any() or .all().
  • __nonzero__ was the Python 2 name; it is ignored in Python 3.