- Home
- Interview Questions
- Python
- Why does using a mutable default argument like a list cause …
Try answering first
In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.
1 Answer
Short answer: Default argument values are evaluated once, when the def statement runs, not on every call. A mutable default such as a list or dict is therefore shared across all calls, so changes made in one call leak into later calls. The standard fix is to default to None and create a new object inside the function.
Detailed explanation
In Python, def is an executable statement. When the interpreter runs it, it builds a function object and evaluates every default expression right then. The resulting values are stored on the function object. Positional defaults go in func.__defaults__. Keyword-only defaults go in func.__kwdefaults__.
On each call where the caller does not supply that argument, Python binds the parameter name to the same stored object. It does not make a copy. This has different effects depending on the type:
- Immutable defaults (int, str, tuple, None, frozenset) are safe. Code that seems to change them really rebinds the local name to a new object.
- Mutable defaults (list, dict, set, custom objects) are risky. Methods like
append,updateoraddchange the shared object in place. That change is still there on the next call.
The same once-only evaluation applies to any expression, not just mutable literals. For example, def log(msg, ts=datetime.now()) records the time the module was imported, not the time of each call.
The idiomatic fix is the None sentinel: use None as the default and build a new object inside the body. If None is itself a valid value callers might pass, use a private sentinel instead, such as _MISSING = object(), and compare with is.
Sometimes a shared mutable default is used on purpose, for example as a simple per-function cache. This works, but it is hidden state. functools.lru_cache or an explicit module-level dict is clearer. Note that dataclasses refuse a list, dict or set default and raise ValueError. You must use field(default_factory=list) there.
Example
def add_item(item, bucket=[]):
bucket.append(item)
return bucket
print(add_item('a')) # ['a']
print(add_item('b')) # ['a', 'b'] same list reused
print(add_item.__defaults__) # (['a', 'b'],)
# Correct version
def add_item(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(add_item('a')) # ['a']
print(add_item('b')) # ['b']
# When None is a meaningful value, use a private sentinel
_MISSING = object()
def get_setting(key, default=_MISSING):
if key in settings:
return settings[key]
if default is _MISSING:
raise KeyError(key)
return default # caller may legitimately pass None
# Dataclasses need default_factory
from dataclasses import dataclass, field
@dataclass
class Cart:
items: list = field(default_factory=list)Printing __defaults__ shows the problem directly. The list is attached to the function object and keeps growing across calls.
Common mistakes
- Writing
bucket = bucket or []orif not bucket:. This also replaces an empty list the caller passed in on purpose. The caller then never sees the items appended to their list. Always test withis None. - Believing Python creates a fresh default on each call. Interviewers want to hear that defaults are evaluated once, at function definition time.
- Thinking only lists are affected. Dicts, sets, class instances and expressions like
datetime.now()oruuid4()show the same once-only behaviour. - Fixing it by copying the default inside the function, for example
bucket = list(bucket). This hides the symptom but makes intent unclear. TheNonepattern is the accepted convention, and linters such as flake8-bugbear (B006) flag mutable defaults.
Follow-up questions
- Where exactly are default values stored on a function object, and how would you inspect them?
- How would you handle a parameter where
Noneis a legitimate value the caller can pass? - Why does a dataclass raise an error for a list default, and what does
default_factorydo?
Interview tip: Show the buggy output first, then say "defaults are evaluated once at def time and stored in __defaults__". That one sentence proves you understand the cause, not just the fix.
Reviewed by the Interview Questions editorial team · Last updated
How well did you know this?
Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.
Your Answer
More medium Python questions
Related Questions
- Why can you call a function declaration before it is defined but not a function expression? · JavaScript · 1 ans
- What is the difference between assignment, shallow copy and deep copy in Python? · Python · 1 ans
- How do positional-only (/) and keyword-only (*) parameters work in Python function signatures? · Python · 1 ans
- What is broadcasting in NumPy and what rules decide whether two arrays can be combined? · Python · 1 ans
- Why does Pandas raise SettingWithCopyWarning and how do you fix chained assignment correctly? · Python · 1 ans
- How do you write a Python decorator that accepts its own arguments? · Python · 1 ans
- What is exception chaining in Python and when should you use raise from? · Python · 1 ans
- In what order do try, except, else and finally blocks run in Python? · Python · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)