compare approaches one problem · two ways
Compare Approaches
The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.
Default argument: [] vs Nonebehaves differently
Add an item to a cart, creating a new cart when none is given. Call it twice.
what differs
Defaults are evaluated once, when def runs. The same list is reused by every call that doesn't pass a cart, so the second call still contains the mug.
at a glance
| approach | use it when |
|---|---|
| A · cart=[] | Never for mutable defaults; it's shown because it's a classic bug. |
| B · cart=None | Any default that's a list, dict or set. |
Watch out: The same applies to dataclass fields: use field(default_factory=list).
the outputs
Each approach runs on the same input.
concepts
default argumentsfunction objects
learn it
Default values and local names
related comparisons
Assignment vs shallow copy vs deepcopy · Hand-written class vs @dataclass