Skip to content

How to Fix Mutable Default Argument Gotcha in Python

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about How to Fix Mutable Default Argument Gotcha in Python. We cover key concepts, practical examples, and best practices.

Python's default argument values are evaluated once at function definition time, not each time the function is called. Mutable defaults like lists and dictionaries accumulate changes across calls.

The Wrong Way

def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item("apple"))
print(add_item("banana"))
print(add_item("cherry"))

Output:

['apple']
['apple', 'banana']
['apple', 'banana', 'cherry']

The list grows with every call, which is usually not intended.

The Right Way

Use None as a sentinel and create a new list inside the function:

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

print(add_item("apple"))
print(add_item("banana"))
print(add_item("cherry"))

Output:

['apple']
['banana']
['cherry']

Step-by-Step Fix

1. Use None sentinel pattern

def process_data(data, cache=None):
    if cache is None:
        cache = {}
    cache[data] = True
    return cache

2. Use a sentinel object for None-like values

_sentinel = object()

def process(data, cache=_sentinel):
    if cache is _sentinel:
        cache = {}
    cache[data] = True
    return cache

This handles cases where None is a valid argument.

3. Use dataclasses with field(default_Factory)

from dataclasses import dataclass, field

@dataclass
class Container:
    items: list = field(default_factory=list)

c1 = Container()
c1.items.append("apple")

c2 = Container()
print(c2.items)  # []

4. Use type hints to document expectations

from typing import Optional

def add_item(item: str, items: Optional[list] = None) -> list:
    if items is None:
        items = []
    items.append(item)
    return items

Prevention Tips

  • Never use mutable objects ([], {}, set()) as default arguments.
  • Use None as the default and create the mutable object inside the function.
  • Use dataclasses.field(default_Factory=...) for class attributes.
  • Use functools.partial to set defaults for pure functions.
  • Enable linter rules that warn about mutable defaults (W0102 in pylint).

Common Mistakes with mutable default

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why do mutable defaults behave this way?

Default arguments are evaluated once when the def statement executes, not each time the function is called. The same list object is reused for every call, accumulating modifications.

Does this happen with all types?

No. Immutable types like integers, strings, and tuples are safe because operations on them create new objects. The problem only affects mutable types: lists, dicts, sets, and custom objects.

How do I detect this bug in existing code?

Use pylint with the W0102 warning, or search for def.*= \[\] and def.*= {} patterns in your codebase. These are almost always bugs.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro