0
0
PythonHow-ToBeginner · 3 min read

How to Implement __bool__ Method in Python Objects

In Python, implement the __bool__ method inside your class to define how instances evaluate to True or False. This method should return True or False and is used by Python when checking the truthiness of an object in conditions like if or while.
📐

Syntax

The __bool__ method is defined inside a class with no parameters except self. It must return a boolean value (True or False).

  • def __bool__(self): — method header
  • Return True or False based on your object's state
python
class MyClass:
    def __bool__(self):
        # Return True or False
        return True
💻

Example

This example shows a class Box that is considered True if it contains any items, and False if empty. The __bool__ method checks the length of the items list.

python
class Box:
    def __init__(self, items):
        self.items = items

    def __bool__(self):
        return len(self.items) > 0

box1 = Box(['apple', 'banana'])
box2 = Box([])

print(bool(box1))  # True
print(bool(box2))  # False

if box1:
    print("Box1 has items")
else:
    print("Box1 is empty")

if box2:
    print("Box2 has items")
else:
    print("Box2 is empty")
Output
True False Box1 has items Box2 is empty
⚠️

Common Pitfalls

Common mistakes when implementing __bool__ include:

  • Returning non-boolean values like integers or strings, which Python treats as True except for zero or empty.
  • Not defining __bool__ or __len__, so the object always evaluates to True.
  • Returning None or forgetting the return statement, which causes __bool__ to return None and raises a TypeError.
python
class WrongBool:
    def __bool__(self):
        return "yes"  # Incorrect: should return True or False

class CorrectBool:
    def __bool__(self):
        return True  # Correct

print(bool(WrongBool()))  # True because non-empty string is truthy
print(bool(CorrectBool()))  # True
Output
True True
📊

Quick Reference

MethodPurposeReturn Type
__bool__(self)Defines truth value of objectTrue or False
__len__(self)Fallback if __bool__ not defined; 0 means FalseInteger (length)

Key Takeaways

Implement __bool__(self) in your class to control its truthiness in conditions.
__bool__ must return True or False, not other types.
If __bool__ is missing, Python uses __len__ to decide truth value.
Returning None or forgetting return causes errors.
Use __bool__ to make your objects behave naturally in if and while statements.