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.
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.
Why Defaults Matter
Immutable vs Mutable Objects
Before understanding the pitfall, you need to know the difference between mutable and immutable objects in Python.
Defaults Are Evaluated Once
Python evaluates default argument expressions once: at the moment the def statement executes, not each time the function is called.
The Mutable Default Trap
Visualizing the Shared Reference
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.
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
Example 1: Shopping Cart
Example 2: Config Dictionary
Example 3: Explicit vs Default
The None sentinel still lets callers pass their own mutable object when they want to:
Inspecting __defaults__
You can see the stored defaults using the __defaults__ attribute on any function object:
Common Mistakes
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?