Python: Function Argument Default Value Wrong

By Xah Lee. Date: . Last updated: .

Python function's default value for argument has side effects.

when you call the function the second time, the default value has its previous value.

same problem in python 2 and 3.

Example:

def f(xx, yy=[]):
    yy.append(xx)
    return yy

print(f(1) == [1])
print(f(1) == [1, 1])  # wtf

this example is from the official Python tutorial. 4. More Control Flow Tools — Python v2.7.6 documentation#default-argument-values

explained as follows:

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.

solution:

make the default to be None, then, in the code, check if it is None, assign the default value you want.

def f(xx, yy=None):
    if yy is None:
        yy = []
    yy.append(xx)
    return yy

print(f(1) == [1])
print(f(1) == [1])

the worst programing language design, yet the python priests write the doc as if it is a great feature.

python function default value 2022-08-25
python function default value 2022-08-25