Python Mutable Defaults: Fix Shared State and Use Factories
Diagnose Python mutable default arguments with identity checks, None and sentinel fixes, shallow-copy limits and dataclass default_factory examples.
A Python function can retain a list between calls even when the caller never passes that list. The usual cause is a mutable default argument: the default expression runs when the function definition executes, and later omitted arguments reuse its result. Fixing the signature is only the first step. You also need to decide whether supplied objects may be mutated, whether None means omission, and whether nested values should be shared. This guide traces those decisions through a complete executable fixture, including dataclass factories.
Why a second call changes the first result
Imagine a helper that collects validation messages. Its first call returns a list containing alpha. A later call adds beta, and code holding the earlier result now sees both messages. Nothing copied beta into the earlier variable. Both variables refer to one list, and append changed that list.
The small example below demonstrates the problem in a fresh Python process. The surprising line is not the second print; it is the last one, showing that the previously returned result changed. Use is to investigate shared identity and == to compare values. Two separate lists can have equal contents without being the same object.
This is an ordinary object-lifetime issue, so reproducing it does not require threads, an async event loop or a web framework. If a request handler uses such a helper, however, repeated requests handled by the same function object can inherit that state. Treat request isolation as a contract to test rather than assuming a new call creates new defaults.
def collect(message, messages=[]):
messages.append(message)
return messages
first = collect('alpha')
print(first) # ['alpha']
second = collect('beta')
print(second) # ['alpha', 'beta']
print(first is second) # True
print(first) # ['alpha', 'beta']Definition time and call time are different events
The default is evaluated when execution reaches def. For a module-level function, that often happens during module initialization. For a nested function, it happens whenever execution reaches the nested definition. “Once” therefore means once for that execution of the definition, not once forever for every function with that source text.
The full fixture uses a make_default function that records evaluations. Defining shared calls make_default once; calling shared twice adds nothing to that evaluation log. A separate build_function example creates two function objects. Calls through f reuse f’s list, while g starts with a different list. This makes the relevant lifetime observable without relying on memory addresses in printed output.
Positional defaults can be inspected through __defaults__; keyword-only defaults are stored in __kwdefaults__. The fixture checks both. These attributes are useful diagnostics, but changing their contents to reset application behavior hides the ownership problem. Repair the function’s initialization policy instead.
Use None when omission and None mean the same thing
For an in-place append helper, items=None followed by if items is None: items = [] gives each omitted call a fresh list. It deliberately gives explicit None the same meaning as omission. Once a caller passes a list, the helper appends to that exact list. That behavior should be visible in the function’s name, documentation and tests.
Use the identity test is None rather than a truthiness shortcut. The expression items = items or [] replaces a valid empty list because an empty list is false in a Boolean context. A caller expecting its supplied list to receive the appended item will instead find it unchanged. The fixture includes both the intended behavior and this faulty repair.
Changing the default does not automatically establish a non-mutating API. If the helper must return a modified copy while leaving the caller’s outer list alone, initialize the local value with list(items) when items is supplied. That is a separate decision from choosing how omitted arguments work. Test the caller’s object after the function returns, not just the returned contents.
| Intended behavior | Initialization policy | Check to retain |
|---|---|---|
| Fresh list when omitted or None | if items is None: items = [] | Separate omitted results have distinct identities |
| Mutate a supplied list | Retain the supplied object | Returned list is the caller’s list |
| Leave supplied outer list unchanged | Copy supplied iterable into a new list | Caller’s outer list is unchanged |
| Preserve explicit None | Use a private omission sentinel | Omission and None produce different results |
Use a sentinel when explicit None has its own meaning
Some APIs distinguish “use the default” from “disable this feature.” If None means disabled, using it as the omission marker loses that distinction. A private object() sentinel supplies a third state: argument absent, explicit None, or a supplied collection. Compare it by identity.
The select_items function in the lab returns a fresh list only for omission and preserves an explicit None. It is a minimal policy demonstration, not a drop-in append helper. A production function that accepts None must define what the rest of its operation does in that state. Do not carry a sentinel into serialized JSON or public API responses.
Keep the sentinel stable for the function’s lifetime. Creating a new object inside the identity comparison would never match the object stored in the signature. If a sentinel appears in an exposed signature, document omission behavior in ordinary words so callers do not need to import an internal implementation object.
Copying the outer list does not isolate nested state
The lab’s caller list contains a dictionary whose labels value is another list. list(caller) creates a different outer list but retains the same nested dictionary. Appending a label through the copied structure changes the original nested data. That result is expected for a shallow copy.
The deepcopy fixture isolates these particular built-in containers, but deep copying is not a universal ownership policy. Objects may customize copying, and resources such as files or sockets are not ordinary recursively copied data. For a configuration object, explicitly reconstructing the fields your function owns can be clearer than duplicating every reachable value.
An immutable outer container does not guarantee immutable contents either. The tuple_default fixture uses a tuple containing a list. The tuple is shared as the default, and its list still accumulates values. Replacing square brackets with parentheses is therefore not a reliable fix unless the entire data structure satisfies the intended immutability contract.
Source: Python standard library: Shallow and deep copy operations ↗
For dataclasses, pass a factory that makes a fresh value
For a list field, field(default_factory=list) supplies a callable rather than a prebuilt list. The generated initializer invokes it when that field is omitted. A supplied field value is used directly. The Job fixture records factory calls, proves that two omitted fields are separate lists, and confirms that an explicit list bypasses the factory and keeps its identity.
Use list, not list(), as the factory. Also inspect what a custom factory returns. A lambda that returns an existing common list meets the callable requirement but gives every instance the same list. The BadFactory counterexample makes that mistake observable; having default_factory in the source is not sufficient evidence of isolation.
Python 3.11 and later reject unhashable dataclass field defaults as an approximation for mutable defaults. The lab confirms that a directly assigned empty list raises ValueError on Python 3.12.14. This guard does not prove every accepted value is immutable. frozen=True also blocks field rebinding rather than recursively freezing contained objects: the fixture can append to a frozen instance’s list while direct field assignment raises FrozenInstanceError.
Source: Python standard library: Dataclass fields and mutable defaults ↗
Run the complete behavior check
Save this listing as mutable_defaults_lab.py and run python3 mutable_defaults_lab.py. It requires Python 3.12 or later and no external packages. The exact published listing was executed on Python 3.12.14. Its records, function names and labels are invented local fixtures; it accesses no services and changes no files.
The expected final line is PASS: 98 checks; definition, call, copy and dataclass boundaries verified. Of those checks, 64 verify the individual contents of retained per-call results. The identity-set check keeps all lists alive while comparing their IDs, avoiding confusion from object IDs being reused after objects are discarded.
The tests intentionally include broken examples. A passing result means those examples exhibited the documented failure and the repaired examples met their stated policy. It does not mean shared defaults, shallow copies or factories that return shared state have become safe to use indiscriminately.
"""Invented local fixtures; Python 3.12+, standard library only."""
from copy import deepcopy
from dataclasses import dataclass, field, FrozenInstanceError
checks = 0
def check(condition, label):
global checks
checks += 1
if not condition:
raise AssertionError(label)
def run():
evaluations = []
def make_default():
evaluations.append('evaluated')
return []
def shared(value, items=make_default()):
items.append(value)
return items
check(evaluations == ['evaluated'], 'definition evaluated the default')
first = shared('alpha')
second = shared('beta')
check(first is second, 'omitted calls share the list')
check(first == ['alpha', 'beta'], 'earlier result changed too')
check(shared.__defaults__[0] is first, 'stored positional default')
check(len(evaluations) == 1, 'calls did not reevaluate expression')
def build_function():
def add(value, items=[]):
items.append(value)
return items
return add
f, g = build_function(), build_function()
check(f('x') is f('y'), 'same function shares its default')
check(f.__defaults__[0] is not g.__defaults__[0], 'new definition, new default')
check(g('z') == ['z'], 'separate function does not inherit f state')
def keyword_only(value, *, items=[]):
items.append(value)
return items
ka = keyword_only(1)
check(keyword_only(2) is ka, 'keyword-only default also shared')
check(keyword_only.__kwdefaults__['items'] == [1, 2], 'keyword default storage')
def append_in_place(value, items=None):
if items is None:
items = []
items.append(value)
return items
a, b = append_in_place('a'), append_in_place('b')
check(a == ['a'] and b == ['b'] and a is not b, 'fresh omitted lists')
check(append_in_place('c', None) == ['c'], 'explicit None follows default policy')
supplied = []
check(append_in_place('d', supplied) is supplied, 'caller-owned empty list retained')
check(supplied == ['d'], 'documented in-place mutation')
def wrong_truthiness(value, items=None):
items = items or []
items.append(value)
return items
empty = []
check(wrong_truthiness('lost', empty) is not empty, 'or replaces caller empty list')
check(empty == [], 'caller list was not updated by truthiness repair')
MISSING = object()
def select_items(items=MISSING):
return [] if items is MISSING else items
check(select_items() == [], 'sentinel creates omitted value')
check(select_items() is not select_items(), 'sentinel fresh per call')
check(select_items(None) is None, 'explicit None preserved')
caller = [{'labels': []}]
shallow = list(caller)
check(shallow is not caller, 'shallow outer list is new')
check(shallow[0] is caller[0], 'nested dictionary still shared')
shallow[0]['labels'].append('shared')
check(caller[0]['labels'] == ['shared'], 'nested mutation crosses shallow copy')
deep = deepcopy(caller)
deep[0]['labels'].append('private')
check(caller[0]['labels'] == ['shared'], 'deep copy isolates these built-in values')
def tuple_default(value, items=([],)):
items[0].append(value)
return items
ta, tb = tuple_default('one'), tuple_default('two')
check(ta is tb and ta[0] == ['one', 'two'], 'tuple contains shared mutable child')
factory_calls = []
def fresh_labels():
factory_calls.append(1)
return []
@dataclass
class Job:
labels: list[str] = field(default_factory=fresh_labels)
j1, j2 = Job(), Job()
check(len(factory_calls) == 2, 'factory called for each omitted field')
check(j1.labels is not j2.labels, 'factory returns independent lists')
j1.labels.append('ready')
check(j2.labels == [], 'second dataclass unaffected')
explicit = []
j3 = Job(explicit)
check(j3.labels is explicit, 'explicit field is not copied')
check(len(factory_calls) == 2, 'explicit field bypassed factory')
try:
@dataclass
class BadJob:
labels: list[str] = []
except ValueError:
check(True, 'direct unhashable field default rejected')
else:
raise AssertionError('expected dataclass ValueError')
common = []
@dataclass
class BadFactory:
labels: list[str] = field(default_factory=lambda: common)
check(BadFactory().labels is BadFactory().labels, 'factory can still return shared state')
@dataclass(frozen=True)
class FrozenJob:
labels: list[str] = field(default_factory=list)
frozen = FrozenJob()
frozen.labels.append('allowed')
check(frozen.labels == ['allowed'], 'frozen does not recursively freeze list')
try:
frozen.labels = []
except FrozenInstanceError:
check(True, 'field rebinding blocked')
else:
raise AssertionError('expected FrozenInstanceError')
# Retain results so identity comparisons cannot be confused by object reuse.
outputs = [append_in_place(i) for i in range(64)]
check(len({id(x) for x in outputs}) == 64, 'all retained results distinct')
for i, result in enumerate(outputs):
check(result == [i], f'per-call state {i}')
print(f'PASS: {checks} checks; definition, call, copy and dataclass boundaries verified')
if __name__ == '__main__':
run()Find the actual owner before changing existing code
When a bug appears only in a full test suite, run the suspected helper twice in the same test and retain both results. Compare identity as well as values. A test that invokes the function only once can miss the state left for the next call. Also test an explicitly supplied empty collection because truthiness repairs often fail there.
Next, trace where the list originates. A global cache, class attribute, closure or factory returning a shared object can recreate the symptom even after the signature uses None. The point is to identify which object is reused and which operation mutates it. Do not assume every cross-call state problem is caused by a default argument.
Before changing a public helper from in-place mutation to copying, inspect its callers. Some may rely on the caller-owned accumulator being updated. Preserving that documented behavior while fixing omission is a smaller compatible change; changing ownership semantics may require a separate migration. Add a regression that names the intended contract so future refactoring does not undo it.
Choose the lifetime that matches the work
Fresh per-call state is the appropriate policy for independent message lists in this guide. Intentionally shared state, such as a cache, deserves an explicit owner, eviction policy and concurrency design. A mutable default can conceal those decisions and make isolation tests harder to interpret. Moving the state to a named component makes its lifetime easier to review.
The lab is single-process and sequential. It does not test locking, concurrent mutation, serialization, framework dependency injection or custom copy hooks. The same ownership questions still matter in those environments, but their behavior needs integration tests with the actual runtime and data types.
Fix the missing-argument behavior, then verify the supplied-argument behavior and nested ownership separately. A None check solves one lifetime problem; a sentinel distinguishes omission; copying defines a new boundary; a dataclass factory initializes an omitted field. Selecting the right combination makes the helper’s state predictable to the next caller.
Your next steps
- Use a fresh allocation inside the function when omitted calls need independent mutable state.
- Test supplied empty collections and nested values before changing mutation or copying semantics.
- Use dataclass factories that actually return fresh objects; frozen fields do not recursively freeze their contents.
Sources & official resources
Linked resources checked on 2026-11-01. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →