__bool__ And bool() Decide Truthiness
Without __bool__, truthiness falls back to __len__, and objects with neither are always truthy — define one to keep empty containers from sneaking through.
Code
class Basket:
def __init__(self, items: list[str]) -> None:
self.items = list(items)
def __len__(self) -> int:
return len(self.items)
class Plain:
pass # neither __bool__ nor __len__: truthiness defaults to True
empty = Basket([])
filled = Basket(["coin"])
print("len fallback:", bool(empty), bool(filled)) # False True:__len__ 决定真值
print("plain object:", bool(Plain())) # True:默认真值
print("if works :", "add item" if not empty else "skip empty")Output
Captured from a sandboxed run of this snippet in the build pipeline.
len fallback: False True
plain object: True
if works : add itemHow it works
bool And bool() Decide Truthiness keeps everything in the classes Basket and Plain and the functions __init__ and __len__.
Applying it
The primary signature is def __init__(self, items: list[str]) -> None
The run emits 2 labeled sections — len fallback:, plain object: — one per step.
Statements that matter
def __init__(self, items: list[str]) -> None:
self.items = list(items)
def __len__(self) -> int:
return len(self.items)
Interactive Tools for This Topic
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `__init__`, `__len__` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.