Skip to content

Mutable default argument bug

Quick summary

You used def f(x=[]) or def f(x={}) — the default is created once at definition time and shared across all calls that use the default.

Why this happens

  • A list, dict, or set is used as a default argument value, which is evaluated once when the function is defined

  • The function modifies the default argument in-place, and the mutation persists to the next call

  • The developer assumed the default is re-created fresh for each call, but Python evaluates defaults at definition time

Minimal example

✗ Broken code
def add_item(item, items=[]):  # mutable default!
    items.append(item)
    return items

print(add_item(1))  # [1]
print(add_item(2))  # [1, 2] — not [2]!
✓ Fixed code
def add_item(item, items=None):
    if items is None:
        items = []  # fresh list each call
    items.append(item)
    return items

print(add_item(1))  # [1]
print(add_item(2))  # [2]

Using None as the default and creating a new list inside the function ensures each call gets a fresh list, preventing state leakage between calls.

How to diagnose

  • Call the function multiple times without the argument and check if the result accumulates unexpectedly

  • Inspect the default argument with print(func.__defaults__) to see if it has been mutated

  • Review any function that modifies its argument in-place and has a mutable default value

How to fix

  • Use None as the default and create the mutable object inside the function body if the argument is None

  • Use an immutable default like a tuple or frozenset if the function does not need to modify it

  • Create a fresh copy of the default inside the function with list(default) or dict(default)

How to prevent

  • Never use mutable objects (list, dict, set) as default argument values — use None and initialize inside

  • Use a linter like flake8-bugbear (B006) that detects mutable default arguments

Related Resources

Related Glossary

Related Lessons

← Back to language