Content · Programming · Python

Python __len__(), __bool__(), and Truth Value Testing

Customize the length and truth value of user-defined objects.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Customize the length and truth value of user-defined objects.

How It Works


__len__() returns a nonnegative integer used by len(); __bool__() controls direct boolean testing and, if absent, Python falls back to length. Explicit __bool__ is useful when truthiness does not equal item count.

__bool__(), when defined, must return a real bool.

Step-by-Step Example


class TaskQueue:
    def __init__(self, tasks):
        self.tasks = list(tasks)

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

queue = TaskQueue(["build", "test"])
print(len(queue))
print(bool(queue))

Understanding the Example


  • The class groups related state and methods so each instance can manage its own values.
  • The function definition gives the operation a reusable name and makes its inputs explicit.

A successful run of this example prints the following output:

2
True

Where This Fits in a Real Program


A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.

Practice: Try It Yourself


Implement an empty queue and compare len() and bool().

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Returning a negative count or non-integer from __len__().
  • Expecting bool(object) to always be True even when its __len__() is zero.

Key Takeaways


  • Customize the length and truth value of user-defined objects.
  • __len__() returns a nonnegative integer used by len(); __bool__() controls direct boolean testing and, if absent, Python falls back to length.
  • __bool__(), when defined, must return a real bool.
Share this resourceSend this page to someone who may find it useful.