Results.

SCEPTRA.TECH

Python Function Remembers the Previous List? Check Mutable Default Arguments

Default list created at definition versus a fresh list created inside each call

A helper that should collect one batch suddenly includes items from the previous call. Restarting the script appears to fix it, but the next batch brings the bug back. Before adding a reset button, I would inspect any list or dictionary in the function's default arguments.

The empty list is not recreated for each call

Python evaluates default argument values when the function definition executes. A list written as a default is one object reused by calls that omit that argument. Appending to it changes the object that later calls receive.

def collect(item, bucket=[]):
    bucket.append(item)
    return bucket

first = collect('alpha')
second = collect('beta')
print(first)            # ['alpha', 'beta']
print(second)           # ['alpha', 'beta']
print(first is second)  # True

Notice that first also shows beta when printed after the second call. The first result was not a snapshot. Both names refer to the shared list, so a later append is visible through either name.

Create the default container inside the function

If omitted input means a fresh collection, a common pattern uses None as the default and checks for it explicitly:

def collect_fresh(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

first = collect_fresh('alpha')
second = collect_fresh('beta')
print(first)            # ['alpha']
print(second)           # ['beta']
print(first is second)  # False

This function treats an omitted argument and an explicit None identically. That is a contract choice. If None is meaningful input that must be distinguished from omission, use a separate sentinel design rather than silently changing that meaning.

The caller's list is still the caller's list

The change fixes sharing of the default. It does not promise that every input is copied. When a caller deliberately passes a list, this version still appends to that same object:

provided = []
result = collect_fresh('gamma', provided)
print(provided)           # ['gamma']
print(result is provided) # True

If the helper must not mutate a supplied list, make that a separate design decision and copy it before editing. A shallow copy creates a new outer list but keeps references to nested objects. It does not make all nested data independent.

Do not substitute a truthiness check

The shortcut bucket = bucket or [] looks similar, but an empty list is false in a Boolean context. It replaces a caller-provided empty list too. That breaks the contract of the accumulating version above: the result gets the new item while the supplied empty list stays empty.

Use bucket is None when None is the designated signal. Testing identity with None says exactly what is absent, without treating every empty collection as missing input.

A small regression test is better than a restart

I ran these examples locally in Python: the original returned the same list for two omitted-argument calls; the corrected version returned separate lists; an explicitly supplied list was mutated; and the truthiness shortcut discarded that supplied empty list. These are focused behavior checks, not tests of an entire import pipeline.

For your helper, test two consecutive omitted-argument calls and inspect the first result after the second call. Then test an explicit empty list, a nonempty list and any documented None behavior. Assert both contents and object identity where ownership matters.

Shared state can be intentional, for example in a cache. The Python FAQ describes that use too. The lesson is not that Python randomly remembers calls. It is that a default object's lifetime and the function's mutation contract must match what the caller expects.

Sources

Comments