I. What Are Default Arguments?
Default arguments (Default Arguments) refer to specifying a default value for a parameter when defining a function. When the function is called without providing the corresponding argument, Python uses this default value.
1. Basic Syntax of Default Arguments
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice")
greet("Bob", "Welcome")
Output:
Hello, Alice!
Welcome, Bob!
Here:
nameis a required parameter and must be provided when calling.messageis a default parameter and can be omitted when calling.- When
messageis omitted, the default value"Hello"is used. - When
messageis explicitly passed, the value provided by the caller is used.
2. Rules for Defining Default Arguments
Among ordinary parameters, parameters with default values must come after parameters without default values.
Correct写法:
def create_user(name, age=18, city="Tokyo"):
print(name, age, city)
create_user("Alice")
create_user("Bob", 25)
create_user("Charlie", 30, "Osaka")
Incorrect写法:
def create_user(name="Alice", age):
pass
This produces a SyntaxError, because an ordinary parameter without a default value cannot appear after an ordinary parameter with a default value.
However, Python also supports other parameter forms such as keyword-only parameters, which have their own ordering rules.
II. When Python Evaluates Default Arguments
This is the most important concept for understanding the default argument pitfalls.
Python evaluates default argument expressions when the function definition statement is executed, not afresh on each function call.
1. Default Arguments Are Initialized Only Once
def show_time(value=10):
print(value)
show_time()
show_time()
show_time()
All three calls use 10.
For immutable objects, this behavior usually causes no problems.
However, if the default value is a mutable object such as a list, dictionary, or set, unexpected results may occur.
2. Observing Default Arguments Using Object Identity
def process(items=[]):
print(id(items))
items.append(1)
print(items)
process()
process()
process()
Possible output:
140000000000000
[1]
140000000000000
[1, 1]
140000000000000
[1, 1, 1]
The memory address here is for illustration only; the actual address depends on the runtime environment.
As you can see:
- Multiple calls use the same list object.
- Each call modifies this list.
- Subsequent calls can see the data left behind by previous calls.
The reason is that the list in the default argument is created when the function is defined, and function calls simply continue to use this object.
3. Lifetime of the Default Argument Object
def append_item(item, container=[]):
container.append(item)
return container
print(append_item("A"))
print(append_item("B"))
print(append_item("C"))
Output:
['A']
['A', 'B']
['A', 'B', 'C']
Execution process:
flowchart TD
A["Execute function definition"] --> B["Create default list"]
B --> C["Store default argument object"]
C --> D["First function call"]
D --> E["Use default list and append element"]
E --> F["Second function call"]
F --> G["Keep using the same list"]
G --> H["Append new element"]
H --> I["Subsequent calls continue sharing this object"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
The key here is not whether the function is called repeatedly, but that the default argument always references the same mutable object.
3. What Is the Mutable Default Argument Trap?
The mutable default argument trap (Mutable Default Argument Trap) refers to when a function uses mutable objects such as lists, dictionaries, and sets as default arguments, multiple calls may share the same object, causing data to be unexpectedly retained between calls.
1. Lists as Default Arguments
Incorrect example:
def add_item(item, items=[]):
items.append(item)
return items
result1 = add_item("Python")
result2 = add_item("Java")
result3 = add_item("Go")
print(result1)
print(result2)
print(result3)
Output:
['Python', 'Java', 'Go']
['Python', 'Java', 'Go']
['Python', 'Java', 'Go']
Why do all three variables get the same content?
Because result1, result2, and result3 all reference the same list object.
You can verify this using object identity:
print(result1 is result2)
print(result2 is result3)
Output:
True
True
2. Dictionaries as Default Arguments
Incorrect example:
def update_config(key, value, config={}):
config[key] = value
return config
config1 = update_config("host", "localhost")
config2 = update_config("port", 8080)
print(config1)
print(config2)
Output:
{'host': 'localhost', 'port': 8080}
{'host': 'localhost', 'port': 8080}
The second call does not modify a brand-new dictionary; it modifies the dictionary used by the first call.
This kind of problem is especially insidious in scenarios such as configuration management, caching, and data processing.
3. Sets as Default Arguments
def add_permission(permission, permissions=set()):
permissions.add(permission)
return permissions
print(add_permission("read"))
print(add_permission("write"))
print(add_permission("delete"))
Output:
{'read'}
{'read', 'write'}
{'read', 'write', 'delete'}
Sets are also mutable objects, so they have the same sharing problem.
4. Nested Mutable Objects Also Pose the Same Risk
Even if the outer container structure looks relatively simple, as long as the default object contains mutable objects, shared state can still occur.
def add_user(name, users={"members": []}):
users["members"].append(name)
return users
print(add_user("Alice"))
print(add_user("Bob"))
Output:
{'members': ['Alice']}
{'members': ['Alice', 'Bob']}
The problem comes from the default dictionary and its internal list being shared across multiple calls.
4. Why are immutable default parameters usually safe?
Common immutable objects in Python include:
- Integer
int - Floating-point number
float - Boolean
bool - String
str - Tuple
tuple - Frozen set
frozenset None
They cannot modify their own state through ordinary in-place operations, so they are usually suitable as default parameters.
1. Using an integer as a default parameter
def calculate(value, multiplier=2):
return value * multiplier
print(calculate(10))
print(calculate(10, 3))
Output:
20
30
Here there is no issue of shared state being modified.
2. Using a string as a default parameter
def greet(name, prefix="Hello"):
return f"{prefix}, {name}"
print(greet("Alice"))
print(greet("Bob"))
Each call uses the same default string object, but the string itself is immutable, so the default parameter will not be modified in place.
3. Tuples require special attention
A tuple is an immutable sequence, but that does not mean every object inside the tuple is immutable.
def process(data=(1, [])):
data[1].append(100)
return data
print(process())
print(process())
Output:
(1, [100])
(1, [100, 100])
Although the tuple itself cannot modify element references, the list inside it can still be modified.
Therefore, to determine whether a default parameter is safe, you cannot look only at whether the outermost container is mutable; you also need to check the objects inside it.
5. Correctly solving the mutable default argument trap
The most recommended solution is to use None as the default value and create a new mutable object inside the function.
1. Using None as a default parameter
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
result1 = add_item("Python")
result2 = add_item("Java")
result3 = add_item("Go")
print(result1)
print(result2)
print(result3)
Output:
['Python']
['Java']
['Go']
A new list is created on each call, so the default list is not shared between different calls.
2. Initializing a dictionary with None
def update_config(key, value, config=None):
if config is None:
config = {}
config[key] = value
return config
config1 = update_config("host", "localhost")
config2 = update_config("port", 8080)
print(config1)
print(config2)
Output:
{'host': 'localhost'}
{'port': 8080}
Whenever config is not passed in, the function creates a new dictionary.
3. Initializing a set with None
def add_permission(permission, permissions=None):
if permissions is None:
permissions = set()
permissions.add(permission)
return permissions
print(add_permission("read"))
print(add_permission("write"))
Output:
{'read'}
{'write'}
4. Execution Flow of the None Approach
flowchart TD
A["Call the function"] --> B{"Is a container argument passed in?"}
B -->|Yes| C["Use the object passed in by the caller"]
B -->|No| D["Default parameter is None"]
D --> E["Create a new container inside the function"]
C --> F["Execute the business logic"]
E --> F
F --> G["Return the processing result"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
This approach has another important advantage: the caller can deliberately pass in an existing container so that the function modifies that container.
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
existing = ["Java"]
result = add_item("Python", existing)
print(result)
print(existing)
Output:
['Java', 'Python']
['Java', 'Python']
Here the function does not create a new list; it uses the list passed in by the caller.
VI. Mutable Default Arguments and Explicit Shared State
Mutable default arguments are not something that must never be used under any circumstances.
Sometimes developers genuinely want multiple calls to share a certain object, such as a cache, a counter, or a state record.
But such behavior should be the result of deliberate design, not an accidental reliance on how default arguments are evaluated.