Python mutable default arguments: fix the shared list

Does a Python list remember earlier function calls? Trace a mutable default, fix it with None, and decide whether a caller's list should change.

PythonBy
Published on

Your function adds an item to a list. The first call looks fine. On the second call, an item from the first one turns up again. The problem starts in the signature, before the function body runs.

In short

Python evaluates a default value such as values=[] when the def statement runs. Calls that omit that argument then use the same list, so mutations remain visible to later calls. Use values=None and create a list inside the body with if values is None: values = []. If the function must also preserve a list supplied by the caller, copy that list before changing it.

Why does the list grow between calls?

Both calls without a second argument change the same object. Keep their return values to see another consequence: the first result changes during the second call too.

shared.pyAvoid
def add(value, values=[]):    values.append(value)    return values
first = add(1)print(first)second = add(2)print(second)print(first)print(first is second)
Terminal
$ python3 shared.py[1][1, 2][1, 2]True

first doesn't hold a snapshot taken at the first return. It refers to the list itself. When the second call appends 2, both names give access to the updated state. The is test checks object identity; comparing values with == would answer a different question.

After both calls, three references to one list

Stack

Python
listadd.__defaults__[0]
shared
listfirst
shared
listsecond
shared

Heap

sharedlist
1021

This is the state after both returns. The calls' local parameters are no longer shown. The function still holds its default value, and first and second still refer to that list.

When does Python create the default value?

Python evaluates the default expression while executing the function definition. The body waits for a call. A small function that prints a message separates those two moments.

definition.py
def make_list():    print("created")    return []
def add(value, values=make_list()):    values.append(value)    return values
print("definition complete")print(add.__defaults__)add(1)add(2)print(add.__defaults__)
Terminal
$ python3 definition.pycreateddefinition complete([],)([1, 2],)

The created message appears before any call to add. Its __defaults__ attribute holds defaults for positional parameters: here, a tuple containing one list. The comma in ([],) belongs to the tuple; it doesn't indicate a second list.

Writing values=list() in the signature wouldn't change when construction happens. Moving construction into the body lets the function decide whether it needs a new object on each call.

How do you fix it with None?

Use None to request a fresh list, and keep a supplied list when the contract allows the function to mutate it. This function accepts a list of integers or None.

fixed.pyCorrect
def add(value, values=None):    if values is None:        values = []    values.append(value)    return values
first = add(1)second = add(2)print(first, second, first is second)supplied = []result = add(7, supplied)print(supplied, result, result is supplied)print(add(3, None))
Terminal
$ python3 fixed.py[1] [2] False[7] [7] True[3]

Calls without a list now produce independent results. Passing supplied still changes that object, even when it starts empty. The fix prevents accidental sharing of the default; it doesn't promise to preserve input lists.

The assignment values = [] changes the local reference. It doesn't turn None into a list or change a list from another call.

Why avoid values or [] and if not values?

An empty list is false in a Boolean context. These shortcuts replace it too, whereas is None keeps it. That matters when the caller expects its list to be filled.

empty_list.pyAvoid
def add(value, values=None):    values = values or []    values.append(value)    return values
empty = []result = add(7, empty)print(empty, result, result is empty)nonempty = [1]result = add(7, nonempty)print(nonempty, result, result is nonempty)
Terminal
$ python3 empty_list.py[] [7] False[1, 7] [1, 7] True

The supplied list changes only when it was already nonempty. That's a surprising contract for an append helper. Writing if not values: values = [] would have the same problem for these inputs.

When None means absence, test for that absence. The same distinction between missing and false values appears in dictionary access and KeyError.

What if the caller's list must stay unchanged?

Copy the list before appending. The contract changes: the result is a new object whether the argument was omitted, empty or already populated.

copying.pyCorrect
def with_added(value, values=None):    result = [] if values is None else values.copy()    result.append(value)    return result
source = [3]first = with_added(1, source)second = with_added(2, source)first.append(9)print(source)print(first, second)print(first is source, first is second)empty = []result = with_added(0, empty)print(empty, result, result is empty)print(with_added(4), with_added(5, None))
Terminal
$ python3 copying.py[3][3, 1, 9] [3, 2]False False[] [0] False[4] [5]

For a list of integers, this copy isolates appends and item assignments. Elements that are themselves lists may remain shared: copying a list of lists covers that extra level.

Python

with_appended

4-bit

Implement with_appended(values, value): return a new list with one integer appended, leaving the input unchanged. This exercise has no optional parameter; it practises the copy contract. Its tests also check two calls on the same list and a later change to the result.

Open the exercise

Frequently asked questions

Does a dictionary default have the same problem?

Yes. Mutating the default dictionary leaves changes visible to later calls. Create the dictionary in the body when each call should have its own state.

Does a function defined inside another function share its default across all creations?

Each execution of the inner def evaluates its own default expressions. Two functions created that way can have distinct lists. Repeated calls to the same function still share its default.

What if None is a valid business value?

Use a distinct sentinel to represent an omitted argument and compare its identity. None works only when its meaning really is "create a new list", as it is here.

Sources

Now write it yourself.