Mutable Default Arguments in Python
A default argument expression is evaluated when Python executes the function definition. A mutable default is shared across calls that omit the argument.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Follow two consecutive calls
A function with default items=[] that appends an input can return [3] on its first omitted-argument call and [3, 5] on the next. Both calls used the same list. The behavior follows object identity and mutation.
Allocate when the call begins
Use an omitted-argument sentinel and create a list inside the body when the sentinel appears. A regression test needs two calls with no explicit list because the first can appear correct. Choose the sentinel so it cannot be mistaken for a deliberate argument.[1][2]
Trace the default object across separate calls
The function def remember(value, seen=[]): evaluates its empty-list default when the definition executes. If its body appends each value and returns the list, a first call with seven returns [7]. A second call with nine appends to the same object, so a reference saved from the first return now also observes [7, 9]. To make each no-argument call independent, default to None and allocate with if seen is None inside the body. See mutable values.
Keep deliberate sharing explicit
A function may allow callers to pass one list intentionally for several operations. Under that design, the explicit list is reused across calls even when the default path creates a new list each time. Test both routes. Replacing the guard by seen = seen or [] would allocate a replacement when a caller explicitly provides an empty list, defeating that sharing policy only at the start. An optional argument with a valid null value needs a different sentinel. See missing values and sentinels.