ZetCode

Python __bool__ Method

Last modified November 17, 2026 Python 3.15

Every object has a truth value. Python uses it in if and while conditions, in the boolean operators, and in the built-in bool() function. A class can define that value with __bool__; if the method is absent, Python falls back to __len__, and if neither exists, the object is true. This article shows how the protocol works and the mistakes that make truth testing surprising.

Truth value testing

For built-in types, Python already knows which values are false: zero numbers, empty strings and containers, None, and False. For an instance of a user-defined class, the default is true unless the class defines __bool__ or __len__.

truthiness.py
values = [0, 0.0, 0j, "", [], {}, set(), None, False, 1, -1, "0", [0]]

for value in values:
    print(f"{value!r:>6} -> {bool(value)}")

The false values include 0, 0.0, 0j, the empty string, empty containers, None, and False. A non-empty string such as "0" is true, and a list containing zero, [0], is true because the list itself is not empty.

$ python truthiness.py
     0 -> False
   0.0 -> False
    0j -> False
    '' -> False
    [] -> False
    {} -> False
 set() -> False
  None -> False
 False -> False
     1 -> True
    -1 -> True
   '0' -> True
   [0] -> True

A basic __bool__ implementation

__bool__ takes only self and should return True or False. It is called by bool(), by if and while, by not, and by the boolean operators. The following account is truthy only while its balance is positive.

account.py
class Account:
    def __init__(self, balance):
        self.balance = balance

    def __bool__(self):
        return self.balance > 0


funded = Account(100)
overdrawn = Account(-50)

print(bool(funded))
print(bool(overdrawn))

if funded:
    print("account has funds")

if not overdrawn:
    print("account is overdrawn")

bool(funded) is True and bool(overdrawn) is False. The if statements call the same method, so the business rule lives in one place. not overdrawn also uses __bool__ and returns a real boolean.

$ python account.py
True
False
account has funds
account is overdrawn

__bool__ must return a bool

Python does not coerce the return value of __bool__ to a boolean. Returning an integer, even 1 or 0, raises TypeError. This is different from a normal function used in an if condition, where any object is accepted.

bad_bool.py
class Flag:
    def __bool__(self):
        return 1


try:
    print(bool(Flag()))
except TypeError as e:
    print(type(e).__name__, e)

The error message names the class and the returned type: Flag.__bool__() must return a bool, not int. Returning NotImplemented fails in the same way. Always return a real bool, for example by wrapping a comparison in bool() if necessary.

$ python bad_bool.py
TypeError Flag.__bool__() must return a bool, not int

The __len__ fallback

If a class has no __bool__, Python calls __len__ and treats a nonzero result as true. If both methods exist, __bool__ wins and __len__ is not consulted. This is why a container's truthiness should normally agree with whether it is empty.

len_fallback.py
class Basket:
    def __init__(self, items):
        self.items = list(items)

    def __len__(self):
        return len(self.items)


class ValidatedBasket(Basket):
    def __bool__(self):
        return any(item != "" for item in self.items)


print(bool(Basket([])))
print(bool(Basket(["apple"])))
print(bool(ValidatedBasket([""])))
print(bool(ValidatedBasket(["apple"])))

Basket defines only __len__, so an empty basket is false and a basket with an apple is true. ValidatedBasket defines both methods. A list with one empty string has length 1, yet __bool__ returns False because the item is empty. That demonstrates the precedence, but it is a poor design for a container: a non-empty container that reports itself as false will surprise callers.

$ python len_fallback.py
False
True
False
True

Errors from __len__

The fallback only works if __len__ follows its own contract: it must return a non-negative integer. A negative result raises ValueError, and a non-integer result raises TypeError. These errors propagate out of bool() rather than being treated as false.

len_errors.py
class NegativeLength:
    def __len__(self):
        return -1


class TextLength:
    def __len__(self):
        return "three"


for obj in (NegativeLength(), TextLength()):
    try:
        print(bool(obj))
    except (TypeError, ValueError) as e:
        print(type(e).__name__, e)

NegativeLength fails with __len__() should return >= 0, and TextLength fails because a string cannot be interpreted as an integer. A class with a broken __len__ does not have a usable truth value.

$ python len_errors.py
ValueError __len__() should return >= 0
TypeError 'str' object cannot be interpreted as an integer

Boolean operators return operands

The and and or operators use truth values but do not return booleans. They return one of their operands: x and y returns x if x is false, otherwise y; x or y returns x if x is true, otherwise y. Only not always returns a boolean.

short_circuit.py
class Account:
    def __init__(self, balance):
        self.balance = balance

    def __bool__(self):
        return self.balance > 0

    def __repr__(self):
        return f"Account({self.balance})"


funded = Account(100)
overdrawn = Account(0)

print(funded and "can withdraw")
print(overdrawn and "can withdraw")
print(overdrawn or "no funds")
print(not overdrawn)

funded and "can withdraw" returns the string because the account is true. overdrawn and "can withdraw" returns the account object itself because the left operand is false. The or expression returns the fallback string, and not returns True.

$ python short_circuit.py
can withdraw
Account(0)
no funds
True

Repeated calls and side effects

A truth test can call __bool__ more than once. The expression probe and probe evaluates the left operand, then evaluates the right operand because the left one was true, so the method runs twice. A side-effect-free method keeps such expressions predictable.

repeated_checks.py
class Probe:
    def __init__(self):
        self.checks = 0

    def __bool__(self):
        self.checks += 1
        return True


probe = Probe()

if probe and probe:
    print("both checks were true")

print(f"__bool__ called {probe.checks} times")

The counter reports two calls. If __bool__ changed state, logged a message, or performed a costly query, the number of calls would depend on how the object is used. Special methods are looked up on the type, so assigning a __bool__ attribute to one instance does not change that instance's truth value.

$ python repeated_checks.py
both checks were true
__bool__ called 2 times

Best practices

Truthiness is part of an object's public interface, so keep it simple:

Source

object.__bool__ - Python documentation

Truth value testing - Python documentation

bool - Python documentation

In this article we have implemented the __bool__ method. We have covered truth value testing, the bool return type, the __len__ fallback, errors from a broken length, the operand-returning behavior of and and or, and repeated calls. For related topics, see Python bool built-in, Python __len__ method, Python any and all, Python control flow, and Python operators.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.