FresherFresher (0–1 yrs)CodingPythonTCSInfosysWipro
mutable default argument pitfall
Why is `def f(a=[])` dangerous in Python? Show the bug and the correct pattern.
Answers use simple, clear English.
Quick interview answer
Default args are evaluated once at function definition. A mutable default is shared across calls — appends accumulate. Correct: use None sentinel and create a new list inside.
Detailed answer
Default args are evaluated once at function definition. A mutable default is shared across calls — appends accumulate. Correct: use None sentinel and create a new list inside. Same for dict/set defaults.
Real example & use case
Helper that accumulates options accidentally shares list between requests.
Pros & cons
Pros of sentinel: fresh mutable each call. Cons: slightly more verbose.
Code example
# bad
def add_bad(x, bucket=[]):
bucket.append(x)
return bucket
# good
def add_good(x, bucket=None):
if bucket is None:
bucket = []
bucket.append(x)
return bucketPractice code · python (view only · no execution)
# bad
def add_bad(x, bucket=[]):
bucket.append(x)
return bucket
# good
def add_good(x, bucket=None):
if bucket is None:
bucket = []
bucket.append(x)
return bucket#python#pitfalls#defaults