01 / 20

Default Arguments
& Mutable Defaults

Master Python's default parameter values, understand why mutable defaults are dangerous, and learn the idiomatic fix every Python developer should know.

Python

What Are Default Arguments?

A default argument is a value assigned to a function parameter in its definition. If the caller omits that argument, Python uses the default instead.

def greet(name, greeting="Hello"): print(f"{greeting}, {name}!") greet("Alice") # Hello, Alice! greet("Bob", "Hey") # Hey, Bob!

Why Defaults Matter

Cleaner API
Callers only pass the arguments they care about, reducing boilerplate.
Backward Compat
Adding a new parameter with a default won't break existing callers.
Self-Documenting
The default value signals the "normal" or expected usage to readers.

Immutable vs Mutable Objects

Before understanding the pitfall, you need to know the difference between mutable and immutable objects in Python.

Immutable
Cannot change after creation: int, float, str, tuple, bool, frozenset
Mutable
Can change in place: list, dict, set, and most custom objects

Defaults Are Evaluated Once

Python evaluates default argument expressions once: at the moment the def statement executes, not each time the function is called.

def time Default object created HERE call 1 Reuses same object call 2 Still the same object! SHARED object

The Mutable Default Trap

def add_item(item, items=[]): items.append(item) return items print(add_item("a")) # ["a"] ← looks fine print(add_item("b")) # ["a", "b"] ← wait, what? print(add_item("c")) # ["a", "b", "c"] ← it keeps growing!

Visualizing the Shared Reference

add_item.__defaults__ ([...],) list object at 0x7f... ["a", "b", "c"] Call 1: add_item("a") Call 2: add_item("b") Call 3: add_item("c") All 3 calls mutate the SAME list!

Python stores the default in the function object's __defaults__ tuple. Since lists are mutable, calling .append() changes the stored default permanently.

The None Sentinel Pattern

The idiomatic fix: use None as the default and create a fresh mutable object inside the function body.

def add_item(item, items=None): if items is None: items = [] # fresh list every call items.append(item) return items print(add_item("a")) # ["a"] print(add_item("b")) # ["b"] ← independent! print(add_item("c")) # ["c"] ← no leaking!

Safe vs Dangerous Defaults

Safe Defaults Dangerous Defaults
Type Immutable Mutable
Examples 0, "", True, None, (1,2) [], {}, set()
Shared? Shared but can't change Shared AND can change
Bug risk None High
Fix needed? No Yes: use None sentinel

Step-by-Step Fix Checklist

1
Check the default value. Is it a list, dict, set, or other mutable object?
2
Replace with None. Change the parameter default to None.
3
Add the guard. At the top of the function body, write if param is None: param = [] (or {} or set()).
4
Test with multiple calls. Verify each call gets an independent object and no state leaks between calls.

Example 1: Shopping Cart

Buggy version
def add_to_cart(item, cart=[]): cart.append(item) return cart alice = add_to_cart("milk") bob = add_to_cart("bread") print(alice) # ["milk", "bread"] ← Bob's bread in Alice's cart! print(bob) # ["milk", "bread"] ← same object!
Fixed version
def add_to_cart(item, cart=None): if cart is None: cart = [] cart.append(item) return cart alice = add_to_cart("milk") bob = add_to_cart("bread") print(alice) # ["milk"] ← correct! print(bob) # ["bread"] ← independent!

Example 2: Config Dictionary

Buggy version
def setup(key, value, config={}): config[key] = value return config print(setup("color", "blue")) # {"color": "blue"} print(setup("size", 10)) # {"color": "blue", "size": 10} ← leaked!
Fixed version
def setup(key, value, config=None): if config is None: config = {} config[key] = value return config

Example 3: Explicit vs Default

The None sentinel still lets callers pass their own mutable object when they want to:

def add_item(item, items=None): if items is None: items = [] items.append(item) return items # Using the default: fresh list each time print(add_item("x")) # ["x"] print(add_item("y")) # ["y"] # Passing an existing list: intentional mutation my_list = ["a", "b"] print(add_item("c", my_list)) # ["a", "b", "c"] print(my_list) # ["a", "b", "c"] ← intentional

Inspecting __defaults__

You can see the stored defaults using the __defaults__ attribute on any function object:

def buggy(items=[]): items.append(1) return items buggy() buggy() print(buggy.__defaults__) # ([1, 1],) ← the default list has been mutated! def fixed(items=None): if items is None: items = [] items.append(1) return items fixed() fixed() print(fixed.__defaults__) # (None,) ← untouched!

Common Mistakes

✕ Using == instead of is
Write if x is None, not if x == None. Identity check (is) is faster and more correct for None.
✕ Forgetting set()
Sets are mutable too. def f(s=set()) has the same bug as lists. Use the None sentinel.
✕ Using [] as "sentinel"
Some try if items == [] to detect the default, but a caller could pass an empty list intentionally. Use None.

Quick Reference Summary

Pattern Buggy Fixed
List default def f(x=[]) def f(x=None)
Dict default def f(d={}) def f(d=None)
Set default def f(s=set()) def f(s=None)
Guard clause if x == [] if x is None: x = []
Int/str default Safe: immutable, no fix needed

Question 1 of 5

When does Python evaluate default argument values?

Question 2 of 5

What is the output of this code?

Question 3 of 5

Which of the following is the correct way to fix a mutable default argument?

Question 4 of 5

Which of these default values is safe (will NOT cause the mutable default bug)?

Question 5 of 5

Why should you use is None instead of == None in the guard clause?