Why does a mutable default argument keep the values from previous calls?
Python mutable default arguments are evaluated once when def runs, so omitted calls share the same list or dict stored in the function's __defaults__. It also connects mutability to the point an interviewer is testing.
Answer
Short answer
A mutable default persists because Python evaluates default expressions once at function definition time. Use None or a private sentinel, then create a fresh list or dict inside the function for each call that omitted the argument.
Was this answer helpful?
Likely follow-ups
- When is a mutable default deliberately useful, for instance as a memoisation cache?
- Why is None a poor sentinel when the caller may legitimately pass None, and what do you use instead?
- Why does a dataclass raise an error for a list default but accept an arbitrary mutable object?
- How would you write a decorator that gives each call a fresh copy of the declared default?
Related questions
- If you were writing a small value type in Python, which dunder methods would you implement, what would you let a dataclass generate, and how does super() decide what to call?mediumAlso on dataclasses4 min
- You need a random number from 1 to 6 and you wrote rand() % 6. What is wrong with that, and when does it stop being merely wrong and become a vulnerability?mediumSame kind of round: concept4 min
- Every number in the array appears three times except one. Find the single number in O(1) extra space, and make sure it works for negatives.mediumSame kind of round: coding5 min
- Implement a FIFO queue using only two stacks, then tell me what a dequeue costs.mediumSame kind of round: coding4 min