JuniorCodeVery commonNot answered yet
What does this mutable default argument print?
Predict the output of these two calls.
def add(item, bucket=[]):
bucket.append(item)
return bucket
print(add(1))
print(add(2))
Determine the output and explain.
[1] then [1, 2]. The default [] is created once, at function-definition time, and reused across calls, so state leaks between them. Fix with a sentinel: def add(item, bucket=None): bucket = [] if bucket is None else bucket.
- ✗Thinking default arguments are re-evaluated on each call
- ✗Expecting a fresh list per call
- ✗Not knowing the None-sentinel fix
- →Why are default arguments evaluated at definition time rather than at call time?
- →How exactly does the
Nonesentinel pattern fix this?