Deepcopy Detaches Nested Mutable State

Assignment aliases and shallow copy shares nested containers; copy.deepcopy alone detaches every level so mutations stop leaking across names.

PythonData Integrity

Code

pythonsnippet
20 lines
import copy

original = {"cart": {"items": ["apple"], "total": 10}}

# 赋值只是别名(alias):两个名字指向同一个嵌套 dict
alias = original
alias["cart"]["items"].append("pear")
print("alias mutated original:", original["cart"]["items"])

# 浅拷贝只复制外层 dict:内层 "cart" 仍然共享
shallow = original.copy()
shallow["cart"]["items"].append("fig")
print("shallow shares cart:", original["cart"]["items"])

# deepcopy 递归复制每一层:嵌套的可变状态彻底独立
original = {"cart": {"items": ["apple"], "total": 10}}
independent = copy.deepcopy(original)
independent["cart"]["items"].append("fig")
print("deepcopy isolated:", original["cart"]["items"])
print("independent copy:", independent["cart"]["items"])

Output

Captured from a sandboxed run of this snippet in the build pipeline.

alias mutated original: ['apple', 'pear']
shallow shares cart: ['apple', 'pear', 'fig']
deepcopy isolated: ['apple']
independent copy: ['apple', 'fig']

How it works

Module-level bindings hold the data — original, alias, shallow, independent — with no function scope in between.

Applying it

Running the file prints labeled results such as alias mutated original:, shallow shares cart:, deepcopy isolated: — each operation’s effect is visible in the output.

Statements that matter

original = {"cart": {"items": ["apple"], "total": 10}}

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `copy`. Its state lives in module-level bindings: `original`, `alias`, `shallow`.