Skip to main content

One passing test can hide shared state in Python

Updated 4 min readMarkdown

The first call returns the expected value. The second contains something you did not pass. Before changing an AI prompt or adding another condition, it helps to inspect when the function creates its state.

I’m building DoesItHold, a project for guided debugging practice. This article is a self-contained teaching example. You can run every example locally without an account or an AI API.

Reproduce two calls

Save this as shared_default.py and run python3 shared_default.py:

def collect(value, items=[]):
    items.append(value)
    return items

print(collect('A'))
print(collect('B'))

The output is:

['A']
['A', 'B']

If the requirement is “start a new collection whenever the caller omits the list,” the second result violates it. If the requirement was deliberately to accumulate values, shared state might be intended. Establish the requirement before calling the behavior a defect.

The default belongs to the function

Python evaluates the default expression when the def statement executes. It does not create a new default list each time the function is called. Both calls that omit items receive the same object.

append changes that object. Returning a copy at the end would not undo the mutation that already happened. Adding a delay would not change object ownership either.

There is a second observation worth making: if you store the first return value and inspect it after the second call, it has changed too. Both references point to the same list. To preserve an observation of the first call for a test, copy the value at observation time; do not confuse that diagnostic copy with a fix.

The Python tutorial on default argument values describes this evaluation rule. The language reference provides the definition-level details.

Make absence explicit

For this contract, None can mean “the caller did not supply a list.” Allocate the list inside the function only in that case:

def collect(value, items=None):
    if items is None:
        items = []
    items.append(value)
    return items

assert collect('A') == ['A']
assert collect('B') == ['B']

supplied = []
assert collect('C', supplied) is supplied
assert supplied == ['C']
print('Independent calls and an explicit empty list: passed')

The last assertions check another part of the contract: a list explicitly supplied by the caller is still used and modified. That behavior is a design choice, not a requirement for every collection function. A function that promises to leave its input untouched needs a different implementation and tests.

The tempting line items = items or [] treats an empty list as false. It therefore replaces a valid empty list supplied by the caller. The explicit is None check preserves that distinction. If None itself is a meaningful user value in another API, use a separate sentinel instead.

Test the sequence, not just the first result

A single successful call cannot demonstrate independence between calls. The smallest useful test here invokes the same function twice without supplying the optional argument.

Be careful with a fixture that creates a fresh function for every assertion: it also creates fresh defaults and can hide the behavior you are trying to investigate. Conversely, a test that depends on a list left over from an unrelated test can become order-dependent. Keep the relevant two calls together and construct a fresh function for the next independent scenario.

The tests in this article check a small function and its declared behavior. They do not run an application, call a model or measure how much someone learned. Passing them does not establish production readiness.

Where the same question becomes useful

A data-processing helper can accidentally retain records from a prior operation. An illustrative chat helper can accidentally retain messages from another call. These contexts make the ownership question worth asking, but this example is not a report of a vulnerability in a product or a complete session-isolation design.

Before accepting a suggested correction, ask: who creates this object, who can change it, and which next call receives it?

The open DoesItHold Python guide contains the corresponding walkthrough and an optional practice entry. Reading it requires no signup. I’m the project’s creator; the explanation and runnable examples above are complete on their own.

What additional test would you write if this function had to leave a supplied list unchanged?

Prepared with AI assistance; examples executed locally and the language rule checked against the Python documentation. All data is synthetic.

6 views

No comments yet. Be the first to comment.