Truth Value Testing (__bool__, __len__) & Short-Circuiting
1Concept
In Python, any object can be tested for truth value. By default, an object is true unless its class defines a `__bool__()` method that returns False or a `__len__()` method that returns zero. Logical `or` and `and` return the actual operand value, short-circuiting evaluation.
2Architecture Diagram
x = a or b ---> If a is truthy, returns a immediately (b never evaluated!) y = a and b ---> If a is falsy, returns a immediately (b never evaluated!)
3Code Example
Python 3.12
class CustomContainer:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
empty_box = CustomContainer([])
full_box = CustomContainer(["Item1", "Item2"])
print(f"Empty box evaluated: {bool(empty_box)}")
print(f"Full box evaluated: {bool(full_box)}")
# Short-circuiting returns operand value
fallback = None or "Default Config"
print(f"Fallback Value: '{fallback}'")4Expected Output
Empty box evaluated: False Full box evaluated: True Fallback Value: 'Default Config'
5Key Takeaways
- ✓`__bool__()` takes precedence over `__len__()` during truth evaluation.
- ✓`a or b` returns `a` if `a` is truthy, otherwise returns `b`.
- ✓Never check booleans with `if x == True:`; always use `if x:`.