How to use and note default arguments in Python functions

Money and Business

Setting a default argument in a Python function definition causes the default value to be used if the argument is omitted during a function call.

The following details are described below.

  • Setting Default Arguments
  • Constraints on the position of default arguments
  • Note that when a list or dictionary is used as the default value

Setting Default Arguments

If argument name = default value in the function definition, the default value will be used when the corresponding argument is omitted.

def func_default(arg1, arg2='default_x', arg3='default_y'):

# a
# default_x
# default_y

func_default('a', 'b')
# a
# b
# default_y

func_default('a', arg3='c')
# a
# default_x
# c

Constraints on the position of default arguments

Placing a default argument before a normal argument (an argument for which no default value is specified) when defining a function results in an error.

# def func_default_error(arg2='default_a', arg3='default_b', arg1):
#     print(arg1)
#     print(arg2)

# SyntaxError: non-default argument follows default argument

Note that when a list or dictionary is used as the default value

If an updatable (mutable) object such as a list or dictionary is specified as the default value, that object will be created when the function is defined. Then, when the function is called without the corresponding argument, the same object is used.

Default argument values are evaluated from left to right when the function definition is executed. This means that the default argument expression is evaluated only once when the function is defined, and the same “calculated” value is used for each call.
8.7. Function definitions — Python 3.10.2 Documentation

Thus, for example, if a function is defined that takes a list or dictionary as its default argument and adds elements to it, and is called multiple times without that argument, elements will be added to the same object repeatedly.

Example for a listing.

def func_default_list(l=[0, 1, 2], v=3):

func_default_list([0, 0, 0], 100)
# [0, 0, 0, 100]

# [0, 1, 2, 3]

# [0, 1, 2, 3, 3]

# [0, 1, 2, 3, 3, 3]

Example for a dictionary.

def func_default_dict(d={'default': 0}, k='new', v=100):
    d[k] = v

# {'default': 0, 'new': 100}

func_default_dict(k='new2', v=200)
# {'default': 0, 'new': 100, 'new2': 200}

A new object is created each time the function is called.

def func_default_list_none(l=None, v=3):
    if l is None:
        l = [0, 1, 2]

# [0, 1, 2, 3]

# [0, 1, 2, 3]
Copied title and URL