Medium: Interview Core · Problem 23 of 82

The Mutable Default Trap

MediumPython BasicsPython

This function is meant to add a tag to a list of tags and return the list:

python def add_tag(tag, tags=[]): tags.append(tag) return tags

It has a bug. Fix it so that:

  • called without a list, it starts from a fresh empty list each time,
  • called with a list, it adds the tag to that same list and returns it (not a copy).

Understand the problem

Predict what the buggy version does.

What do these two lines print, with the buggy add_tag above?

print(add_tag("a"))
print(add_tag("b"))
  1. ["a"] then ["b"]
  2. ["a"] then ["a", "b"]
  3. An error

The default list [] is created once, when the def statement runs, not each time the function is called. Every call that uses the default shares that one list, so the tags pile up.

When is the default value [] in def add_tag(tag, tags=[]) created?

  1. Each time add_tag is called
  2. Once, when the def statement is executed
  3. Only the first time add_tag is called

Default values are evaluated when the function is defined. That is harmless for numbers, strings and None (they cannot change), and a trap for lists, dicts and sets (they can).

Fix the bug

Edit the code in the box. The tests check the two rules in the task.

# This code has a bug. Fix it so the two rules in the task hold.
def add_tag(tag, tags=[]):
    tags.append(tag)
    return tags
Hint 1: a question to ask yourself

Which value can you use as a default that cannot be changed, and still tells you "no list was given"?

Hint 2: the shape of the answer

Use None as the default. Inside the function, if tags is None, create a new list. Use is None, not if not tags: an empty list that the caller passes in must still be used.

Reflect

Solution

def add_tag(tag, tags=None):
    if tags is None:
        tags = []
    tags.append(tag)
    return tags

What this tests: when default arguments are evaluated, mutable versus immutable values, and is None.

The standard fix: use None as the default and create the list inside the function. This is such a common pattern that linters warn about mutable defaults.

Why is None and not or: tags = tags or [] looks shorter, but an empty list passed by the caller is falsy, so it would be thrown away and replaced by a new one. The caller's list would not be updated, which breaks the second rule.

When a shared default is useful: a default dict used as a cache is sometimes done on purpose. Say so in a comment, so the next reader knows it is not an accident.

What an interviewer might ask next: Does the same trap apply to a default of {} or set()? What about a default of datetime.now()? (Both are evaluated once, at definition.)