Python: Keyword Argument Default Value Unstable

By Xah Lee. Date: . Last updated: .

Keyword argument's default value is unstable.

Example:

# -*- coding: utf-8 -*-
# python 2

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

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

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:

# -*- coding: utf-8 -*-
# python 2

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

print f(1)  # [1]
print f(1)  # [1]

Why Python Sucks

Syntax

Semantics