Python: Keyword Argument Default Value Unstable

, , …,

the hideousness of Python.

Keyword argument's default value is not unstable. Example:

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

print f(1)                      # [1]
print f(1)                      # [1, 1]
print f(1)                      # [1, 1, 1]
print f(3, [7,8])               # [7, 8, 3]
print f(4)                      # [1, 1, 1, 4]

this example is from the official Python tutorial. http://docs.python.org/2/tutorial/controlflow.html#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:

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

print f(1)                      # [1]
print f(1)                      # [1]
print f(1)                      # [1]
print f(3, [7,8])               # [7, 8, 3]
print f(4)                      # [4]
blog comments powered by Disqus