ToolTrap
← All learning guides

Python · ToolTrap learning guide

Python: avoid sharing a function's default list

Trace an unexpected shared list, replace the mutable default with None, and test whether two calls really return independent results.

The bug looks like remembered history

You are writing a helper that adds a concept to a study list. You expect a fresh list when the caller does not supply one. The following implementation looks compact, but its output shows why a mutable default can make separate calls affect each other. Run the example with Python 3.

def add_concept(name, concepts=[]):
    concepts.append(name)
    return concepts

first = add_concept('Docker')
second = add_concept('Git')
print(first)
print(second)
print(first is second)

Both prints show ['Docker', 'Git'], and the identity check prints True. The list used as the default was created when Python executed the function definition. Omitting the second argument reuses that list; it does not create a new one for each call.

Create a list inside each call

Use None to represent an omitted list, then allocate the list inside the function. Testing with is None is intentional. A caller may pass an empty list that should be used, so a broad test such as if not concepts would treat a valid empty list like a missing argument.

def add_concept(name, concepts=None):
    if concepts is None:
        concepts = []
    concepts.append(name)
    return concepts

first = add_concept('Docker')
second = add_concept('Git')
assert first == ['Docker']
assert second == ['Git']
assert first is not second

These assertions verify both values and independence. Checking only the final value could miss a sharing bug when two callers happen to want the same content.

Decide whether to mutate a supplied list

The corrected helper still changes a list explicitly supplied by the caller. That may be useful, but it should be a deliberate contract. Suppose a screen stores selected concepts and asks the helper to append Python. The screen's original selection now changes too, because both names refer to the same list.

If you want a helper that leaves the caller's list alone, copy the sequence before appending. For a flat list of strings, this makes a separate outer list. With nested mutable objects, a shallow copy still shares those inner objects, so do not assume it isolates every possible change.

def with_concept(name, concepts=None):
    result = [] if concepts is None else list(concepts)
    result.append(name)
    return result

selected = ['Linux']
updated = with_concept('Python', selected)
assert selected == ['Linux']
assert updated == ['Linux', 'Python']

Check your understanding

Question 1: When is the default [] in the original function created? Answer: when the function definition is executed, rather than once per call.

Question 2: Why use is None instead of testing whether the supplied list is empty? Answer: an empty list can be a valid caller-owned object that the function should respect.

Question 3: Which helper leaves selected unchanged: add_concept or with_concept? Answer: with_concept, because it creates a separate list before appending.

When reviewing a Python helper, look for mutable defaults such as lists, dictionaries and sets. Run two calls without arguments, then one call with an explicitly supplied object. Those examples reveal whether the function's behavior matches what its caller expects.

Explore the official documentation

Use these references to check command options and continue your practice.