Python mutable defaults: decide who owns the input
Fix omitted-argument leakage separately from caller-owned input mutation; use a strict job-configuration boundary with schema-aware reconstruction instead of indiscriminate deepcopy.
Quick answer
Python creates a function default when the function is defined, so a mutable default can retain state across calls. Allocate omitted defaults inside the function, then define whether supplied input is borrowed or copied. For independent nested configuration, validate and reconstruct the supported structure, and test mutations from both directions.
On this page
Fix a Python mutable default by allocating the default inside the function, then decide separately whether supplied input may be mutated. Replacing {} with None prevents omitted calls from sharing that default dictionary. It does not copy a caller's dictionary or its nested values. An API that promises independent job settings must define both the default lifetime and the ownership of supplied objects. [1][2][3]
Why does the next call inherit the previous job?#
The function's default object survives between calls. Python evaluates a default when the function is defined, rather than allocating it each time the caller omits the argument. Mutating that object changes what a later omitted call receives. This behavior is documented; it is not a race condition that requires concurrent execution. [1][2]
Scenario: a hypothetical export service constructs settings for each job. A helper appends a job-specific tag to a default list, and a later export unexpectedly contains the earlier tag. The example is invented to expose the lifetime problem. No customer incident or production data is implied.
def broken_tags(job_name, tags=[]):
tags.append(job_name)
return tags
first = broken_tags("catalog")
second = broken_tags("inventory")
assert first is second
assert second == ["catalog", "inventory"]The result returned by the earlier call changes too, because both variables refer to the same list. Looking only at the latest return value misses that consequence. Check the latest result and the earlier list that the caller still holds.
Use identity to investigate sharing. Equality answers whether values currently compare equal; is answers whether references identify the same object. Independent empty lists compare equal before either is changed, so equality alone cannot establish independent ownership. The Python data model distinguishes object identity from value. [5]
This also explains why a process restart can appear to repair the symptom. Defining the function again creates another default object, temporarily clearing its accumulated state. Restarting does not change the ownership contract. Reproduce the issue with consecutive calls inside the same process before adding threads or asynchronous tasks to the test.
What does changing the default to None actually fix?#
It fixes allocation for omitted input when None is your chosen marker for absence. Allocate the mutable object after checking that marker explicitly. Python's tutorial and FAQ both describe this approach. [1][2]
def append_tag(job_name, tags=None):
if tags is None:
tags = []
tags.append(job_name)
return tags
a = append_tag("catalog")
b = append_tag("inventory")
assert a == ["catalog"] and b == ["inventory"]
assert a is not b
provided = []
assert append_tag("catalog", provided) is provided
assert provided == ["catalog"]The final assertions are intentional: this helper still mutates supplied input. That can be a valid API for an accumulator whose caller owns and expects the change. It is unsuitable if callers expect a job builder to leave their configuration untouched. The same implementation can therefore pass a default-lifetime test and fail the desired application contract.
Avoid substituting tags = tags or [] without considering supplied empty containers. An empty list is false in a Boolean context, so this expression replaces it. A non-empty list is retained and mutated. An API that sometimes borrows the caller's container and sometimes replaces it is difficult to reason about unless that distinction is deliberate.
If None is a legitimate configured value, use a separate sentinel to represent omission. That is a semantic decision, not a requirement to make every function more elaborate. Document whether explicit None means reset, inherit, disable or reject. Callers should not have to discover the difference by observing mutations.
Choose the contract for supplied input#
For a job builder, we would choose independent output with validation at the boundary. The caller can reuse a settings object for multiple jobs, and changing a built job must not modify that settings object or another job. State this promise before choosing a copy operation.
Assignment does not satisfy it. Python assignment binds a name to an object rather than cloning it. A shallow dictionary copy creates a new outer container but retains references to the values. If a value is a list, changing that list through the copied dictionary can still affect the original. [3]
template = {"tags": ["nightly"], "headers": {"X-Mode": "export"}}
shallow = dict(template)
assert shallow is not template
assert shallow["tags"] is template["tags"]
shallow["tags"].append("catalog")
assert template["tags"] == ["nightly", "catalog"]List the mutable containers a caller can reach through the returned job. Copying the root helps only when the promised independence stops there. If the contract includes the tag list and header mapping, those containers need independent ownership too.
Deep copying is an option, but it should not replace a domain decision. Python's copy documentation explains that deep copying recursively copies compound objects and can copy more than intended. Some objects customize copying, and resources such as sockets are not ordinary configuration data. An API accepting arbitrary live Python objects cannot promise that deepcopy creates a meaningful independent job. [3]
| Boundary choice | Useful when | Review question |
|---|---|---|
| Borrow and mutate | Caller deliberately provides an accumulator | Is the mutation explicit and observable? |
| Shallow copy | Only the outer container needs isolation | Are nested mutable values intentionally shared? |
| Deep copy | The accepted object graph has meaningful copy behavior | Could copying duplicate something that should be shared? |
| Reconstruct known fields | The API accepts a small configuration schema | Are unknown fields rejected or deliberately preserved? |
For the export example, reconstruction is a practical choice because the accepted structure is small. It makes the supported data types visible and avoids pretending that arbitrary nested objects are valid configuration. This is our design recommendation, not a rule imposed by Python.
How should a small configuration boundary copy data?#
Validate the accepted shape and allocate the mutable containers that the output owns. The following illustrative builder accepts string tags, string header pairs and a nonnegative integer retry limit. It rejects unknown fields so that a new caller setting cannot be silently dropped.
from collections.abc import Mapping
def build_job(job_name, options=None):
if not isinstance(job_name, str) or not job_name:
raise ValueError("job_name must be a nonempty string")
if options is None:
options = {}
if not isinstance(options, Mapping):
raise TypeError("options must be a mapping or None")
unknown = set(options) - {"tags", "headers", "retry_limit"}
if unknown:
raise ValueError("unknown option keys")
tags = options.get("tags", [])
headers = options.get("headers", {})
retry_limit = options.get("retry_limit", 0)
if not isinstance(tags, list) or not all(
isinstance(tag, str) for tag in tags
):
raise TypeError("tags must be a list of strings")
if not isinstance(headers, Mapping) or not all(
isinstance(key, str) and isinstance(value, str)
for key, value in headers.items()
):
raise TypeError("headers must map strings to strings")
if type(retry_limit) is not int or retry_limit < 0:
raise ValueError("retry_limit must be a nonnegative integer")
return {
"name": job_name,
"tags": [*tags, job_name],
"headers": dict(headers),
"retry_limit": retry_limit,
}The builder deliberately accepts only a narrow data model. The output owns a new root dictionary, tag list and header dictionary. Their contents are strings or the validated integer, so this schema does not admit a nested mutable object requiring another copy policy. If the schema later adds nested delivery rules, update both reconstruction and the ownership tests.
The strict integer check is also deliberate: the example rejects Boolean retry limits rather than interpreting them as configuration counts. Whether that is the right contract for another application is a separate decision. Validation should make the intended accepted inputs explicit, especially when a broad language type relationship is narrower than a business field's meaning.
This function does not establish an atomic snapshot of a concurrently mutated input mapping. It reads fields and validates them before constructing output. If another actor may mutate the input during those reads, arrange synchronization or pass already-stable data at the call boundary. Independent output after construction and consistent input during construction are different requirements.
Likewise, this is configuration validation, not credential handling. A caller should not place long-lived secret objects into an unrestricted dictionary and assume that copying makes their lifecycle safe. Keep the schema small enough that reviewers can identify what crosses the boundary.
Changing an existing helper to this contract needs a caller review. A caller may deliberately inspect the dictionary after the helper mutates it. Replacing that behavior with independent output can be a breaking change even though it removes surprising sharing elsewhere. Find those callers, decide whether mutation is part of the supported API, and give them an explicit return-value path before changing the implementation.
For a private helper, that migration may be a small patch with updated call sites. For a public library, preserve the documented behavior or introduce a separately named operation with a clear transition. Do not hide a contract change inside a patch described only as replacing a mutable default. Default allocation and supplied-input mutation are separate review decisions, and each deserves a regression case.
The schema also establishes what independence excludes. Strings and the validated count can be reused as values; the builder does not need to manufacture another string object to satisfy the promise. The mutable root, tag list and header dictionary are the containers that must be independent. Tests that require every value to have a different identity would overstate the contract and reject harmless sharing of immutable values. [3][5]
Do dataclasses or read-only views settle ownership?#
They solve narrower problems. A dataclass field with default_factory=list can allocate a list when a default is needed. The factory belongs to the default path; explicitly passing a list is a different path that still needs the intended ownership decision. Python documents default and default_factory as mutually exclusive field settings. [4]
from dataclasses import dataclass, field
@dataclass
class JobSettings:
tags: list = field(default_factory=list)
left, right = JobSettings(), JobSettings()
assert left.tags is not right.tags
shared = []
explicit = JobSettings(tags=shared)
assert explicit.tags is sharedDo not call the factory while declaring it. Passing a callable and passing the result of calling it are different operations. Also inspect what the callable returns: a factory that repeatedly returns a module-level list still shares that list. Test what the factory returns; its name cannot establish that the list is fresh.
A read-only mapping view is another distinct choice. MappingProxyType prevents writes through that mapping interface, but it is a dynamic view of the underlying mapping. It is neither a detached snapshot nor a recursive freeze of nested values. The types documentation describes the view's relationship to its source mapping. [6]
from types import MappingProxyType
source = {"tags": ["nightly"]}
view = MappingProxyType(source)
source["mode"] = "full"
assert view["mode"] == "full"
view["tags"].append("catalog")
assert source["tags"] == ["nightly", "catalog"]The example does not mean read-only views are ineffective. They are useful when an API should prohibit writes through one interface while intentionally reflecting another owner's changes. That is a different promise from the job builder's independent configuration.
How can a review catch the bug before concurrency hides it?#
Test consecutive omitted calls, explicit empty input and nested supplied values in a deterministic process. Then mutate the output and inspect the input and another output. Reverse the direction too: mutate the original after construction and confirm the built job remains unchanged.
For build_job, start with a template containing a tag list and header dictionary. Build separate jobs from the same template. Append a tag and change a header in one result. The template and the other result must retain their original values. Follow that with rejected-input cases: a nested tag object, a non-string header value, an unknown field and an invalid retry limit.
These checks test the public promise instead of only asserting that the source contains None. A source-level check can detect a common spelling of a mutable default, but it cannot establish that a factory returns fresh state or that supplied nested input is isolated.
Our Python callback binding guide covers a related but separate question: when a delayed callback selects a value. Here the focus is state reused across function invocations and ownership of supplied configuration. Fixing either problem does not automatically settle the other.
The examples follow Python 3.14 documentation. The local fixtures ran on Python 3.9.6; verify the same input and mutation cases on the interpreter your application ships. They do not demonstrate thread safety, production throughput or behavior of arbitrary third-party model libraries. Run the ownership fixtures on the interpreter and schema you actually ship. [1][3][4]
Questions about default lifetime#
- Is None required for every mutable parameter?
- No. It is a common absence marker when explicit
Nonecan share the omitted-input meaning. Use a separate sentinel when those meanings differ. A required mutable argument has no default-lifetime bug, though its ownership still needs a contract. [1][2] - Does dict(options) make all nested data independent?
- It creates a new outer dictionary while retaining references to its values. Nested lists and dictionaries can remain shared. Decide which containers require isolation, then reconstruct or copy that structure according to the accepted schema. [3]
- Does default_factory copy a list I pass explicitly?
- No. The factory supplies a default when one is needed. An explicitly provided value follows the constructor's supplied-input path. If the class promises independent ownership of that input, implement and test that separate behavior. [4]
- Can I intentionally keep state in a default?
- Python permits it, and the FAQ discusses caching as an intentional use. The concern is hidden lifecycle and ownership. An explicit cache object or instance usually makes that state easier to discover, reset and test. [2]