Data Model

Truth and Size

__bool__ and __len__ decide how objects behave in truth tests and len().

__len__ lets len() ask an object for its size.

Source

class Inbox:
    def __init__(self, messages):
        self.messages = list(messages)

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

print(len(Inbox(["hi", "bye"])))

Output

2
x__bool__()__len__() != 0default: True
bool(x) calls __bool__ first; if absent, __len__() != 0; if neither, defaults to True.

If a class has __len__ but no __bool__, Python uses zero length as false.

Source

print(bool(Inbox([])))

Output

False

__bool__ expresses truth directly when the answer is not just container size.

Source

class Account:
    def __init__(self, active):
        self.active = active

    def __bool__(self):
        return self.active

print(bool(Account(False)))

Output

False

Notes

See also

Run the complete example

Example code

Expected output

2
False
False

Execution time appears here after you run the example.