Friday, June 5, 2026

How does Python determine the truth value of an object if __bool__ is not implemented?

All Questions From This Chapter    « Previously    Next »

When Python needs to determine if an object is “truthy” or “falsy” (for example in an if statement or bool(obj)), it follows a specific fallback order:

  1. __bool__ – Python first looks for a __bool__ method on the object. If present, it calls that method and uses the boolean result directly.

  2. __len__ – If __bool__ is not implemented, Python next looks for a __len__ method. If that exists, it calls __len__() and treats the object as True if the result is non-zero, and False if the result is 0.

  3. Default True – If neither __bool__ nor __len__ is defined, the object is considered True by default. (This applies to most user-defined class instances unless they explicitly define one of the two methods.)

Thus, the truth value is False only if:

  • The object defines __bool__ and it returns False, or

  • The object does not define __bool__ but defines __len__ and __len__() returns 0.

Otherwise, it is True.

Example with a custom class

python
Copy
Download
class AlwaysTrue:
    pass                    # no __bool__, no __len__

class EmptyContainer:
    def __len__(self):
        return 0

class NonEmptyContainer:
    def __len__(self):
        return 5

class ExplicitFalse:
    def __bool__(self):
        return False

# Testing
print(bool(AlwaysTrue()))       # True (default)
print(bool(EmptyContainer()))   # False (__len__ returns 0)
print(bool(NonEmptyContainer()))# True (__len__ returns 5)
print(bool(ExplicitFalse()))    # False (__bool__ returns False)

Why this order?

It allows built-in types like lists, strings, and dicts to be “falsy” when empty without needing a special __bool__. They just implement __len__:

python
Copy
Download
bool([])      # False – list.__len__ returns 0
bool([1,2])   # True  – list.__len__ returns 2

Objects that want to be unconditionally True can leave both methods undefined. If you want to make an object explicitly falsy, define __bool__ to return False.

This mechanism is defined in Python’s Truth Value Testing rules.


All Questions From This Chapter    « Previously    Next »

No comments:

Post a Comment