Default Parameter Values in Python Functions
In Python, you can set default values for function parameters. If a function is called without providing a specific argument, the default value is used.
For a basic understanding of Python functions, see:
Set Default Parameter Values
You can set default values in a function definition using the format parameter_name=default_value
. If the corresponding argument is omitted during the function call, the default value will be used.
def func_default(arg1, arg2='default_x', arg3='default_y'):
print(arg1)
print(arg2)
print(arg3)
func_default('a')
# a
# default_x
# default_y
func_default('a', 'b')
# a
# b
# default_y
func_default('a', arg3='c')
# a
# default_x
# c
Position Constraints for Default Parameters
When defining a function, you cannot place a parameter with a default value before a parameter without a default value. Doing so raises a SyntaxError
.
# def func_default_error(arg2='default_a', arg3='default_b', arg1):
# print(arg1)
# print(arg2)
# SyntaxError: parameter without a default follows parameter with a default
Notes on Using Mutable Objects as Default Values
Mutable default values like lists or dictionaries are created when the function is defined and reused in subsequent calls if the corresponding argument is omitted.
Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call.
8. Compound statements - Function definitions — Python 3.13.3 documentation
Consider a function that uses a list or dictionary as a default parameter and adds elements to it. When the function is called multiple times without providing that argument, elements will be added to the same object repeatedly.
Example with a list:
def func_default_list(l=[0, 1, 2], v=3):
l.append(v)
print(l)
func_default_list([0, 0, 0], 100)
# [0, 0, 0, 100]
func_default_list()
# [0, 1, 2, 3]
func_default_list()
# [0, 1, 2, 3, 3]
func_default_list()
# [0, 1, 2, 3, 3, 3]
Example with a dictionary:
def func_default_dict(d={'default': 0}, k='new', v=100):
d[k] = v
print(d)
func_default_dict()
# {'default': 0, 'new': 100}
func_default_dict(k='new2', v=200)
# {'default': 0, 'new': 100, 'new2': 200}
To avoid this behavior, you can use None
as the default value and create a new object inside the function. This ensures that a new object is created each time the function is called without the argument.
def func_default_list_none(l=None, v=3):
if l is None:
l = [0, 1, 2]
l.append(v)
print(l)
func_default_list_none()
# [0, 1, 2, 3]
func_default_list_none()
# [0, 1, 2, 3]