Tech challenge · Python

Tags leak between records

EasyPython

A helper adds a tag to a record's tag list. After processing a batch, every record has the tags of all previous records:

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

Explain the bug and fix it.

Think it through or sketch an answer first, then open the hint or the solution.

Show a hint

When is the default value created: on every call, or once?

Show the solution

Default values are evaluated once, when the def runs, so every call that omits tags shares the same list object. Use None as the default and create a new list inside the function.

Example (Python)

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

Common mistakes

  • Copying the list on return: the shared default still grows on every call.
  • Assuming this only affects lists: dicts, sets and any other mutable default behave the same way.

Learn more

More Python challenges

Today's challenge and the full archive