Data Model
Truth and Size
__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
2If 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
FalseNotes
- Prefer
__len__for sized containers. - Prefer
__bool__when truth has domain meaning. - Keep truth tests unsurprising; surprising falsy objects make conditionals harder to read.
See also
- prerequisite: Truthiness
- related: Special Methods
- related: Container Protocols
Run the complete example
Expected output
2
False
False
Execution time appears here after you run the example.