Skip to the solution
MediumDSA8 min read

Why is using a mutable default argument dangerous?

1.0k views

The problem

Question presented to candidate: "Here is def add_item(item, bucket=[]): bucket.append(item); return bucket. Call it twice without a bucket. What do you get, why, and how would you fix it?"

What a strong answer should cover:

  • Default expressions are evaluated once, when the def statement executes, not on every call; the resulting object is stored on the function in __defaults__ (or __kwdefaults__)
  • So a mutable default ([], {}, set(), a custom object) is one shared object; mutations from one call leak into every later call that relies on the default
  • The fix: None as a sentinel and create the object inside the body; a private object() sentinel when None is a valid input; field(default_factory=list) in dataclasses
  • The same "evaluated once" rule explains def f(ts=datetime.now()) freezing a timestamp, and the class-attribute version of the bug
  • Linters catch it (Ruff / flake8-bugbear B006, Pylint W0102 dangerous-default-value), and the deliberate exception: a default dict used as a cache, usually better done with functools.lru_cache

Code / implementation expected: Yes β€” reproduce the bug, show __defaults__ changing, then write the None-sentinel version.

  • mutable-default

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

8 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonThe shared default list, seen through __defaults__, and the sentinel fixes
PythonSame rule elsewhere: def-time evaluation, dicts, class attributes, dataclasses, a deliberate cache

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 50 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is composition versus inheritance?

Continue