Python Functions · Lesson 71 of 149

Python Mutable Defaults and Function Traps

What you will learn

  • The mutable default argument trap, and why it happens
  • The None pattern that fixes it
  • When a shared default is useful on purpose
  • Other common function traps and how to avoid them
  • A short checklist for reviewing a function

1. The trap

Here is a function that adds an item to a list. If you do not give a list, it should start with a new, empty one:

def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item("a"))
print(add_item("b"))
print(add_item("c", ["x"]))
print(add_item("d"))
['a']
['a', 'b']
['x', 'c']
['a', 'b', 'd']

Look at the second call. It gave ['a', 'b'], not ['b']! The list remembered the earlier call. And the fourth call, add_item("d"), returned ['a', 'b', 'd']: it found the same list that the first two calls used. Only the third call, which passed its own list, behaved as expected.

Quick check: why did `add_item("b")` return `['a', 'b']`?

The default list is created only once and shared by every call that does not pass its own list.

2. Why it happens

You learned in lesson 11.3 that a default is worked out once, when the def line runs. For a number or a string, that is harmless, because they cannot be changed. But [] creates one list object, which is stored with the function. Every call without an argument gets that same list, and append changes it in place (lesson 2.6).

You can see the stored default with __defaults__:

print(add_item.__defaults__)
print(add_item.__defaults__[0] is add_item("e"))
(['a', 'b', 'd'],)
True

The list inside __defaults__ is the list that the calls return. It has grown, call by call. It happens with any mutable default: a list, a dictionary, a set, or an object you created, such as list():

def counts(word, seen={}):
    seen[word] = seen.get(word, 0) + 1
    return seen

print(counts("a"))
print(counts("a"))
print(counts("b"))
{'a': 1}
{'a': 2}
{'a': 2, 'b': 1}

The same dictionary keeps counting across calls, which is almost never what you want.

The same "worked out once" rule affects time defaults: def stamp(t=datetime.datetime.now()) returns the moment the function was defined on every call.

3. The fix: None

Use None as the default, and make the fresh object inside the function, where it is made again on every call:

def add_item2(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

print(add_item2("a"))
print(add_item2("b"))
print(add_item2("c", ["x"]))
print(add_item2.__defaults__)
['a']
['b']
['x', 'c']
(None,)

Now each call without a list gets a new one. The stored default is just None, which cannot change. Test with is None (and not if not items), so that an empty list that the caller passed is still used, and not silently replaced:

Test What happens when the caller passes an empty list []
if items is None: the caller's list is used, as intended
if not items: a new list replaces the caller's, so their list is never filled

4. Safe defaults

Only mutable defaults are a problem. These defaults are safe, because they cannot change:

Safe default Example
numbers, text, booleans rate=0.5, sep=" ", verbose=False
None items=None
a tuple (of immutable items) items=()
a frozenset allowed=frozenset()
def tuple_default(items=()):
    return items + (1,)

print(tuple_default())
print(tuple_default((5,)))
(1,)
(5, 1)

items + (1,) makes a new tuple, so the default is never changed. An empty tuple is a fine stand-in for an empty list when you only read the items.

5. When a shared default is useful

Because the default lives as long as the function, you can use it on purpose as a private store, for example a cache (lesson 11.6):

def cached(n, cache={}):
    if n not in cache:
        cache[n] = n * n
    return cache[n]

print(cached(3), cached(3))
print(list(cached.__defaults__[0].items()))
9 9
[(3, 9)]

This works, but it looks like the bug to a reader. It needs a comment, and for real programs functools.lru_cache (lesson 17.5) or a module-level dictionary is clearer.

6. Other traps

Using the result of an in-place method

Methods such as sort, append and reverse change the object and return None (lessons 7.2 and 7.4):

def no_return(lst):
    lst.sort()

data = [3, 1]
data = no_return(data)
print(data)
None

Either return lst at the end (and document that it sorts in place), or, better, return a new sorted list: return sorted(lst).

Returning internal state

If a function returns a mutable object that it also keeps, the caller can change your private data:

_store = []

def returns_internal():
    return _store

a = returns_internal()
a.append(1)
print(_store)
[1]

Return a copy to protect it: return list(_store) (lesson 7.5).

A path with no return

A function whose if has no else returns None for the other case (lesson 11.1), which can crash the code that uses the answer:

def maybe(n):
    if n > 0:
        return n

print(maybe(1) + 1)
print(maybe(-1) + 1)
2
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Empty or odd input

Test a function with empty and extreme input (lesson 6.7). Many functions fail only then:

def first_word(text):
    return text.split()[0]

def avg(nums):
    return sum(nums) / len(nums)

first_word("")
avg([])
IndexError: list index out of range
ZeroDivisionError: division by zero

Decide what each should do for empty input: return a default, or raise a clear error with a message (lesson 11.8).

A loop variable that may not exist

def last_index(n):
    for i in range(n):
        pass
    return i

print(last_index(3))
last_index(0)
2
UnboundLocalError: cannot access local variable 'i' where it is not associated with a value

When the loop runs zero times, i never gets a value (lesson 11.5).

A swap that goes nowhere

Rebinding the parameter names does not change the caller's names (lesson 11.2):

def swap_wrong(a, b):
    a, b = b, a

x1, y1 = 1, 2
swap_wrong(x1, y1)
print(x1, y1)
1 2

Return the swapped pair instead: x1, y1 = swap(x1, y1).

Silent keyword typos

A function with **kwargs accepts any name, even a misspelled one, and ignores it:

def kw(**opts):
    return opts.get("colour", "none")

print(kw(color="red"))
print(kw(colour="red"))
none
red

The American spelling color was quietly ignored. If a function has a fixed set of options, list them as named parameters so that a typo gives a TypeError.

Comparing with None

Write value is None, not value == None. Both work for plain values, but a class can change what == means, while is None always asks the right question (lesson 2.6).

More traps from earlier lessons

  • Lambdas in a loop all see the last value (lesson 11.7).
  • Naming a variable list, sum, max or id hides the built-in (lesson 11.5).
  • print is not return (lesson 11.1).
  • A function that changes its input and also returns it invites confusion (lesson 11.2).

7. A review checklist

Before you trust a function, ask:

Question Why
Is any default a list, dictionary or set? use None
Does every path end in a return (or is None intended)? avoid surprise None
Does it change its input? If so, is that stated? no hidden effects
Does it return internal state? return a copy
What happens with empty input, zero, one item, and a bad type? edge cases
Does it use global variables? prefer arguments and return values
Is the docstring accurate? lesson 11.8

Worked example: repair a buggy function

A to-do list function has three bugs. Find and fix them.

# the buggy version
def add_task(task, tasks=[], urgent=False):
    if urgent:
        tasks.insert(0, task)
    else:
        tasks.append(task)

todo = add_task("wash")
print(todo)

The function returns nothing, so todo is None (bug 1). A call without a list shares the default list between calls (bug 2). And urgent could be mistyped positionally (bug 3).

Fixed version:

def add_task(task, tasks=None, *, urgent=False):
    """Return a new task list with task added (at the front if urgent)."""
    new = [] if tasks is None else list(tasks)
    if urgent:
        new.insert(0, task)
    else:
        new.append(task)
    return new

first = add_task("wash")
second = add_task("cook", first)
third = add_task("call", second, urgent=True)
print(first)
print(second)
print(third)
print(add_task("sleep"))
['wash']
['wash', 'cook']
['call', 'wash', 'cook']
['sleep']
Bug Fix
nothing returned return new
shared default list tasks=None, and make new inside
the caller's list changed by accident list(tasks) makes a copy, so each result is a new list
urgent easy to pass by mistake keyword-only with * (lesson 11.3)

The last line, add_task("sleep"), starts from a fresh list, not from the earlier ones. The tasks are made up.

Common mistakes

  • Using [], {} or set() as a default argument.
  • Testing if not items instead of if items is None.
  • Returning a private mutable object instead of a copy.
  • Assigning the result of sort() or append().
  • Not testing the empty case.
  • Writing **kwargs when a fixed set of named options would catch typos.

Key takeaways

  • A default is worked out once, so a mutable default (list, dictionary, set) is shared by all calls.
  • Fix it with None as the default, and create the fresh object inside; test with is None.
  • Numbers, text, booleans, None, tuples and frozensets are safe defaults.
  • Return copies of internal state, make sure every path returns, and test empty input.
  • **kwargs hides typos; named parameters catch them.

Practice

1. What does def f(x, seen=[]): do wrong?

Show answer

The empty list is created once and shared by every call that does not pass seen, so changes pile up between calls.

2. Rewrite it correctly.

Show answer
def f(x, seen=None):
    if seen is None:
        seen = []
    ...

3. Why is items=() a safe default but items=[] is not?

Show answer

A tuple cannot be changed, so sharing it is harmless. A list can be changed in place, so the shared list changes.

4. Why should you test if items is None and not if not items?

Show answer

not items is also true for an empty list that the caller passed, so you would replace the caller's list with a new one. is None replaces it only when nothing was given.

5. What is result after result = my_list.sort()?

Show answer

None, because sort() sorts in place and returns nothing. Use sorted(my_list) for a new list.

6. Name two edge cases to test for a function that takes a list.

Show answer

An empty list, and a list with one item. Also a list with repeats or an unexpected type.