One function, two calls
What does this print?
def add_item(item, basket=[]):
basket.append(item)
return basket
print(add_item("apple"))
print(add_item("pear"))Most people expect ["apple"] and then ["pear"]. Each call gets an empty basket by default, adds one thing, and returns it.
The second line actually prints ["apple", "pear"].
When is the default created?
The answer hangs on one question: when does Python build that []?
Not when the function is called. It is built once, when the def line runs, and stored with the function. Every call that does not pass a basket gets that same stored list. Not a copy. The same one.
1def add_item(item, basket=[]):2 basket.append(item)3 return basket45print(add_item("apple"))6print(add_item("pear"))
What exists in memory
nothing yet
Start. Press play, or step through one line at a time.
The def line runs once
Python creates the function, and creates the default list alongside it.
The first call uses that list and changes it
appendmodifies the list in place.The function ends. The list does not
It belongs to the function, not to the call.
The second call receives the same list
It still contains what the first call put there.
You can see the stored list directly:
>>> add_item.__defaults__
(['apple', 'pear'],)Why only some defaults are a problem
Defaults like count=0 or name="" behave exactly as you would hope. The difference is whether the value can be changed in place.
| Default value | Can it be changed in place? | Safe as a default? |
|---|---|---|
0, 3.5, True | No | Yes |
"text" | No | Yes |
None | No | Yes |
(1, 2) (a tuple) | No | Yes |
[] (a list) | Yes | No |
{} (a dict) | Yes | No |
set() | Yes | No |
A number is shared between calls too. But count += 1 does not alter the number 0. It makes count point at a new number. The stored default is untouched. A list is different: append changes the list itself, and everyone holding that list sees the change.
The fix
Use None as the default and build the real value inside the function, where the code runs on every call.
1def add_item(item, basket=None):2 if basket is None:3 basket = []4 basket.append(item)5 return basket67print(add_item("apple"))8print(add_item("pear"))
Variables
nothing yet
Start. Press play, or step through one line at a time.
def add_item(item, basket=None):
if basket is None:
basket = []
basket.append(item)
return basketThis pattern is so standard that experienced Python programmers type it without thinking, and code checkers warn about a list or dict used as a default.
Key takeaways
- A default argument is created once, when the function is defined, not on each call.
- Every call that relies on the default shares the same object.
- That is harmless for values that cannot change, such as numbers, strings and None.
- It is a bug for lists, dicts and sets, because changes made by one call are seen by the next.
- Use None as the default and create the list inside the function.