The Mutable Default Trap
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"))
["a"]then["b"]["a"]then["a", "b"]- 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?
- Each time
add_tagis called - Once, when the
defstatement is executed - Only the first time
add_tagis 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.)
VISIBLE = 3
CASES = [
('result = add_tag("a")', ['a'], 'a fresh list'),
('add_tag("a")\nresult = add_tag("b")', ['b'], 'the second call must not remember the first'),
('mine = ["x"]\nr = add_tag("y", mine)\nresult = (r is mine, mine)', (True, ['x', 'y']), 'a given list is changed and returned'),
('add_tag("p")\nadd_tag("q")\nresult = add_tag("r")', ['r'], 'many calls'),
('mine = []\nr = add_tag("y", mine)\nresult = (r is mine, mine)', (True, ['y']), 'an empty list given by the caller is still used'),
('result = add_tag("a", [])', ['a'], 'a new empty list given'),
]