A shallow copy duplicates a container’s outer references; a deep copy recursively copies supported reachable state while tracking already-copied objects.
Python shallow and deep copies: preserve aliases deliberately
Operation contract
Two dispatch entries intentionally reference one shared label list. A shallow copy of their dictionary still references the original list. Deepcopy creates a separate list but preserves the relationship between the two fields within the copied graph. That alias preservation matters: deep copying does not mean every path becomes an unrelated object.
Failure and ownership boundary
Files, sockets and arbitrary custom objects are not automatically meaningful snapshots. Classes can override copying, and a graph may contain cycles. For domain snapshots, a fresh immutable data representation is often easier to audit than recursively copying a live service object. Python dataclasses: frozen fields require an immutable value model and Python inventory project: validate a batch before replacing stored state cover alternatives.
Working program
from copy import copy, deepcopy
labels = ["checked"]
batch = {"first": labels, "second": labels}
shallow = copy(batch)
owned = deepcopy(batch)
owned["first"].append("packed")
print(shallow["first"] is labels)
print(owned["first"] is owned["second"])
print(labels)
print(owned["second"])Output
True
True
['checked']
['checked', 'packed']Costs and limits
An outer dictionary copy takes O(n) reference work. Deepcopy cost depends on the reachable graph and custom hooks; visited-object bookkeeping prevents copying the same supported object repeatedly, but there is no general constant-cost snapshot.
Common Mistakes
- A deep copy can preserve shared references inside the copied graph.
- Do not treat copying live I/O handles as an application recovery plan.
Connected lessons
Python variables: names refer to objects, assignment does not copy, Python dataclasses: frozen fields require an immutable value model, Python inventory project: validate a batch before replacing stored state.
