How to Fix Mutable Default Argument Gotcha in Python
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
Noneas the default and create the mutable object inside the function. - Use
dataclasses.field(default_Factory=...)for class attributes. - Use
functools.partialto set defaults for pure functions. - Enable linter rules that warn about mutable defaults (
W0102in pylint).
Common Mistakes with mutable default
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- 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
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro