Fix Mutable Default Arguments in Python Functions
Why def add(item, items=[]) shares the same list across every call, and how items=None fixes it.
By the end of this tutorial you will know:
- When Python evaluates default argument values (at
deftime, not call time) - Why
items=[]orcache={}leaks data between unrelated calls - The standard
Nonesentinel pattern to fix it
Prerequisites: Python 3 installed.
1. The big idea
In Python, a function's default arguments are evaluated once when the def statement runs—not each time you call the function. If the default value is a mutable object like a list ([]) or dict ({}), every call that omits that argument mutates the exact same object in memory.
2. Reproducing the bug
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
print(add_tag("python"))
print(add_tag("go"))You might expect ["python"] and ["go"]. Instead, you get:
['python']
['python', 'go']3. The fix: default to None
Use None (which is immutable) as the default value, and create a fresh list inside the function body whenever tags is None.
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
print(add_tag("python"))
print(add_tag("go"))['python']
['go']Run python3 fixed.py. Each call without a second argument now returns its own independent list.
4. Common pitfalls
| Mistake | Symptom | Fix |
|---|---|---|
def f(cache={}): | User A sees User B's cached data | Use cache=None and if cache is None: cache = {} |
if not items: instead of if items is None: | Caller's empty list is ignored | Always check is None |
5. What you learned
You now know why mutable default arguments share state in Python and how the None sentinel pattern keeps function calls isolated.