How do mutable default arguments create a subtle memory and correctness pitfall related to object lifetime?
Short answer
A mutable default argument (like a list or dict) is created once when the function is defined, not each time it's called -- so all calls that don't override the argument share and mutate the same object, causing unexpected state to persist and accumulate across calls, which is…
Advertisement
AModel answer
A mutable default argument (like a list or dict) is created once when the function is defined, not each time it's called -- so all calls that don't override the argument share and mutate the same object, causing unexpected state to persist and accumulate across calls, which is both a correctness bug and an unintended long-lived memory reference.
def append_item(item, target=[]): # BUG: default list created once
target.append(item)
return target
print(append_item(1)) # [1]
print(append_item(2)) # [1, 2] -- unexpected! Same list reusedReal-world example
A web request handler using a mutable default dict parameter for 'options' accidentally leaks state between unrelated requests, causing one user's settings to bleed into another's response.
Likely follow-ups
- Why does Python evaluate default arguments only once?
- What's the standard fix using None as sentinel?
Related topics