[ACCEPTED]-Optional parameters in functions and their mutable default values-optional-parameters

Accepted answer
Score: 51

Good doc from PyCon a couple years back 6 - Default parameter values explained. But basically, since lists are mutable 5 objects, and keyword arguments are evaluated 4 at function definition time, every time 3 you call the function, you get the same 2 default value.

The right way to do this would 1 be:

def F(a, b=None):
    if b is None:
        b = []
    b.append(a)
    return b
Score: 10

Default parameters are, quite intuitively, somewhat like member 15 variables on the function object.

Default 14 parameter values are evaluated when the 13 function definition is executed. This means 12 that the expression is evaluated once, when 11 the function is defined, and that same “pre-computed” value 10 is used for each call. This is especially 9 important to understand when a default parameter 8 is a mutable object, such as a list or a 7 dictionary: if the function modifies the 6 object (e.g. by appending an item to a list), the 5 default value is in effect modified.

http://docs.python.org/reference/compound_stmts.html#function

Lists 4 are a mutable objects; you can change their 3 contents. The correct way to get a default 2 list (or dictionary, or set) is to create 1 it at run time instead, inside the function:

def good_append(new_item, a_list=None):
    if a_list is None:
        a_list = []
    a_list.append(new_item)
    return a_list

More Related questions