Optional parameters in functions and their mutable default values

55,683

Solution 1

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

The right way to do this would be:

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

Solution 2

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

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

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

Lists are a mutable objects; you can change their contents. The correct way to get a default list (or dictionary, or set) is to create 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
Share:
55,683

Related videos on Youtube

Oscar Mederos
Author by

Oscar Mederos

Bachelor's Degree in Computer Science (5 years). Interested in: Open Source, Functional Programming, Web Scraping/Automation, Web Development, Containers and any other programming/CS related subject. Contact me at omederos[at]gmail.com

Updated on May 05, 2020

Comments

  • Oscar Mederos
    Oscar Mederos about 4 years

    Possible Duplicate:
    “Least Astonishment” in Python: The Mutable Default Argument

    I'm kind of confused about how optional parameters work in Python functions/methods.

    I have the following code block:

    >>> def F(a, b=[]):
    ...     b.append(a)
    ...     return b
    ...
    >>> F(0)
    [0]
    >>> F(1)
    [0, 1]
    >>>
    

    Why F(1) returns [0, 1] and not [1]?

    I mean, what is happening inside?

    • sam
      sam about 13 years
      you can see that easily just by printing the value of b before appending to the list. :)