Decide which edits may travel
An archive report can have a new outer list and still expose the input's tag lists to an editor. The question is which objects an edit can reach through its references. A fresh variable name or a value-equality check cannot answer that question.
By the end, predict an aliasing defect, distinguish rebinding from mutation, and repair a copy boundary that protects both the original records and other drafts. Use identity checks on the relevant lists/dictionaries, without assuming numeric memory addresses or interpreter reference counts.
The archive-contract lesson established distinct sources, ordered records and preserved tag values. Today uses trusted records constructed directly in Python, with the same source/name/ tags shape. The .json source labels identify records; no JSON files, manifest, parser or complete archive CLI are used here. Copying is not schema validation.
Use the approved final standard GIL-enabled CPython 3.15.1 from lesson 1. Only the standard library is needed; no previous environment, cache, package installation, service or account is required. The exercised route is macOS ARM64/zsh. Other operating systems and interpreter builds remain unverified for this walkthrough.
Names, objects and edges
An object has an identity, a type and a value. A name is bound to an object; assignment of a name does not recursively duplicate its contents. Two names bound to the same object are aliases. A list contains references to its elements, and a dictionary associates keys with referenced values.
A mutable object can change in place. Appending to a list changes that list;
rebinding a name to a different list changes the name's binding. Neither action
magically redirects every other reference to the old object. In this lesson,
is asks whether two expressions reach the same object; == compares values
of the built-in lists/dictionaries and their contents. Equal values can belong
to different objects. Custom equality and key contracts come in the next lesson.

Figure: selected mutable objects immediately after alias, shallow and deep are created, before any edit. A, B, C, R1, R2, T1 and T2 are diagram labels, not numeric object IDs. Every arrow carries an object reference.
Read from the names downward. original and alias both reach A. The shallow copy creates B, but its element still reaches R1; following R1's tags field therefore reaches T1 from either outer list. The deep copy reaches C, then R2, then T2. T1 and T2 initially hold the same tag value. Immutable string objects and other implementation details are deliberately omitted from the drawing. This is a graph of the selected reference relationships, not a memory layout.
A shallow copy creates a new outer container and retains references to its contents. For the built-in lists/dictionaries here, their copy methods supply that operation. A deep copy recursively copies supported compound values and uses a memo to remember objects already copied in that operation. A memo is a mapping from an original object to its corresponding copy. It avoids repeatedly copying the same object and supports recursive graphs. It can preserve sharing within the copied graph. It does not promise a separate object for every path through that graph.
Set up a fresh reference experiment
Run this command group in zsh. The shown interpreter is the author-tested
existing path; substitute only your already approved executable if needed.
&& stops the group after a failure:
AP_PYTHON='/opt/homebrew/bin/python3.15' &&
"$AP_PYTHON" -VV &&
AP_REFERENCES_ROOT="$(mktemp -d -t advanced-python-references)" &&
printf '%s\n' 'advanced-python:lesson-4' > "$AP_REFERENCES_ROOT/.advanced-python-owner" &&
cd "$AP_REFERENCES_ROOT" &&
pwd
Retain the exact printed root and the two variables in this terminal. Stop on failure; if the terminal closes, restore those exact saved values. A marker helps catch an ordinary wrong-directory mistake; it is not a filesystem sandbox. All source data is supplied below, so no earlier local files are consumed.
Trace the actual paths
Before running, predict the tag values after the nested edit, after the slot replacement, and after the deep-copy memo example. Save this complete original file as trace_references.py in the marked root:
from copy import deepcopy
from pathlib import Path
import sys
if (sys.implementation.name != "cpython"
or sys.version_info[:3] != (3, 15, 1)
or sys.version_info.releaselevel != "final"):
raise SystemExit("STOP: final CPython 3.15.1 required.")
if sys.abi_info.free_threaded or not sys._is_gil_enabled():
raise SystemExit("STOP: standard GIL-enabled build required.")
if sys.flags.optimize:
raise SystemExit("STOP: run these self-checks without -O or -OO.")
owner = Path(".advanced-python-owner")
if owner.is_symlink() or not owner.is_file() or owner.read_text(encoding="utf-8").strip() != "advanced-python:lesson-4":
raise SystemExit("STOP: use the marked lesson-4 root.")
original = [
{"source": "records/oak-a.json", "name": "Oak ledger", "tags": ["local"]},
]
alias = original
shallow = original.copy()
deep = deepcopy(original)
assert alias is original, "alias should reach the original list"
assert shallow == original == deep, "initial values differ"
assert shallow is not original and deep is not original, "copy reused the original outer list"
assert shallow[0] is original[0], "shallow element should be shared"
assert shallow[0]["tags"] is original[0]["tags"], "nested tags should be shared"
assert deep[0] is not original[0], "deep record should be separate"
assert deep[0]["tags"] is not original[0]["tags"], "deep tags should be separate"
print("before: equal values, different reference paths")
shallow[0]["tags"].append("reviewed")
assert original[0]["tags"] == alias[0]["tags"] == ["local", "reviewed"]
assert deep[0]["tags"] == ["local"]
print("nested edit:", original[0]["tags"], deep[0]["tags"])
shallow[0] = {"source": "records/oak-a.json", "name": "Oak ledger", "tags": ["draft-only"]}
assert original[0]["tags"] == ["local", "reviewed"]
assert shallow[0]["tags"] == ["draft-only"]
assert shallow[0] is not original[0]
alias = []
assert alias == [] and len(original) == 1
print("slot replacement:", shallow[0]["tags"], original[0]["tags"])
print("name rebound:", len(alias), len(original))
shared_tags = ["local"]
pair = [
{"source": "records/oak-a.json", "name": "Oak ledger", "tags": shared_tags},
{"source": "records/oak-b.json", "name": "Oak ledger", "tags": shared_tags},
]
cloned = deepcopy(pair)
assert cloned[0]["tags"] is cloned[1]["tags"], "one deep pass preserves this sharing"
assert cloned[0]["tags"] is not shared_tags, "copy must be separate from input"
cloned[0]["tags"].append("reviewed")
assert cloned[1]["tags"] == ["local", "reviewed"]
assert shared_tags == ["local"]
print("memo:", cloned[1]["tags"], shared_tags)
print("trace self-checks: passed")
The first guards check implementation, final release, build capability and current GIL state separately. The optimization guard refuses -O/-OO because assert statements can be omitted in optimized execution. The ordinary marker guard checks this root before the experiment. These are the same context checks taught earlier, resupplied so this checkpoint is independent of old files.
The first record dictionary has a tag list. alias = original adds a binding
without copying. original.copy() copies the outer list only. deepcopy is
imported from the standard-library copy module and, for this plain nested
list/dictionary example, creates separate mutable record/tag containers. The
initial assertions connect the drawing's arrows to runtime observations. The
chained equality check verifies initial values; the identity checks verify
relationships that value equality alone cannot establish.
shallow[0]["tags"].append("reviewed") follows the shallow list's element to
the shared dictionary and then its tag list. That append changes T1. It is
visible through original and alias, while deep still has its original value.
By contrast, assigning a new dictionary to shallow[0] changes B's element
reference; it does not replace A's element. The later alias = [] rebinds
only that name. original still refers to its nonempty list.
The final pair intentionally puts the same tag list in two distinct source records. A single deepcopy call copies that list once and reuses its copy for both cloned records. Appending through one cloned record therefore changes the other's tags; it does not affect shared_tags in the input. This is correct deep-copy behavior for this graph, and may be wrong for a proposed editing policy.
Run, compare your predictions, then rerun unchanged:
"$AP_PYTHON" -I -B trace_references.py
Illustrative output (the current author execution matched these values):
before: equal values, different reference paths
nested edit: ['local', 'reviewed'] ['local']
slot replacement: ['draft-only'] ['local', 'reviewed']
name rebound: 0 1
memo: ['local', 'reviewed'] ['local']
trace self-checks: passed
These scripts print observations only. They do not write reports, launch workers or access the source-label paths. Each new process reconstructs its small input, so a normal unchanged rerun starts from the same values.
Repair the boundary required by an editor
Suppose prepare_drafts must return equal initial values in the original source order, in a new outer list with a new dictionary per record and a private tag list per draft. Editing any draft must leave the input and its peer draft unchanged, even when the input records share tags. Empty input returns an empty list. Immutable source/name strings need no new identity; preserve their values. This is an explicit editing policy, not a new accepted archive-record field.
Save this complete original repair_boundary.py in the same root:
from pathlib import Path
import sys
if (sys.implementation.name != "cpython"
or sys.version_info[:3] != (3, 15, 1)
or sys.version_info.releaselevel != "final"):
raise SystemExit("STOP: final CPython 3.15.1 required.")
if sys.abi_info.free_threaded or not sys._is_gil_enabled():
raise SystemExit("STOP: standard GIL-enabled build required.")
if sys.flags.optimize:
raise SystemExit("STOP: run these self-checks without -O or -OO.")
owner = Path(".advanced-python-owner")
if owner.is_symlink() or not owner.is_file() or owner.read_text(encoding="utf-8").strip() != "advanced-python:lesson-4":
raise SystemExit("STOP: use the marked lesson-4 root.")
def prepare_drafts(records):
drafts = []
for record in records:
draft = record.copy()
draft["tags"] = record["tags"].copy()
drafts.append(draft)
return drafts
shared_tags = ["local", "local"]
records = [
{"source": "records/oak-b.json", "name": "Oak ledger", "tags": shared_tags},
{"source": "records/oak-a.json", "name": "Oak ledger", "tags": shared_tags},
]
expected_input = [
{"source": "records/oak-b.json", "name": "Oak ledger", "tags": ["local", "local"]},
{"source": "records/oak-a.json", "name": "Oak ledger", "tags": ["local", "local"]},
]
drafts = prepare_drafts(records)
assert drafts == expected_input and drafts is not records, "draft values/order differ"
assert drafts[0] is not records[0], "draft record still touches input"
assert drafts[0]["tags"] is not records[0]["tags"], "draft tags still touch input"
assert drafts[0]["tags"] is not drafts[1]["tags"], "draft records share tags"
drafts[0]["tags"].append("reviewed")
expected_drafts = [
{"source": "records/oak-b.json", "name": "Oak ledger", "tags": ["local", "local", "reviewed"]},
{"source": "records/oak-a.json", "name": "Oak ledger", "tags": ["local", "local"]},
]
assert records == expected_input, "editing a draft changed the input"
assert drafts == expected_drafts, "edit escaped the selected draft"
assert prepare_drafts([]) == [], "empty draft batch changed"
print("input:", records[0]["tags"], records[1]["tags"])
print("drafts:", drafts[0]["tags"], drafts[1]["tags"])
print("boundary self-checks: passed")
prepare_drafts builds a new outer list. Each record.copy() creates a shallow
dictionary copy, which initially still refers to the input's tags. Replacing
only that copied dictionary's tags field with record["tags"].copy() gives
this draft its own list. Repeating this step per record intentionally breaks
the input's cross-record tag sharing. The string values need no recursive copy.
For this declared list-of-strings shape, one copy of the tag list is sufficient.
A schema with deeper mutable values would require a different justified boundary.
The two source records deliberately share a list with a repeated tag value. expected_input is a value prediction, not a set or a copy of the live data. The pre-edit checks establish the chosen identities. The complete post-edit prediction checks count/order/source/name/tag values together and requires the unselected draft and input to keep both repeated tags. The empty-batch check adds a boundary case; it cannot by itself expose nested sharing.
Run this complete group:
"$AP_PYTHON" -I -B repair_boundary.py &&
printf '%s\n' 'current boundary run succeeded'
Illustrative output:
input: ['local', 'local'] ['local', 'local']
drafts: ['local', 'local', 'reviewed'] ['local', 'local']
boundary self-checks: passed
current boundary run succeeded
Now expose two distinct faults, one at a time. Keep the complete file's checks unchanged; restore the supplied function after each attempt.
First replace only prepare_drafts with this deliberate faulty function excerpt, not another complete program:
def prepare_drafts(records):
return records.copy()
Predict the first failed check, then run the same group. The new outer list passes its check, but its first dictionary still touches the input. The AssertionError should name that relationship. The shell's success message must not run. A new outer list was insufficient.
Restore the supplied function, then remove only the line that copies tags, leaving record.copy() and the rest of the loop. Predict and run again. This time the record dictionaries differ, but the tag-identity check fails. Follow the remaining shared edge rather than adding copies without a declared policy. Restore the complete function and require a successful current rerun.
Assertions are enabled developer checks for these supplied cases, not production input validation or proof over all inputs. Diagnose the first failed invariant; do not erase it, accept current output as the prediction or use -O to conceal it. A syntax/name error from an incomplete edit is different from the intended aliasing failure: restore the complete file, rerun it, then apply one edit again.
Check Your Understanding
Attempt these before opening the reasoning. Preserve the supplied originals so restoration does not depend on remembering an unrecorded edit.
-
Replace only prepare_drafts with this comparison excerpt, leaving all checks and input unchanged. Predict which check fails, whether the input tags are copied, and whether the two drafts have independent tags. Run and explain why isolating the input alone is insufficient for the editor's policy.
def prepare_drafts(records): from copy import deepcopy return deepcopy(records) -
Restore the original function. Change the edit from draft zero to draft one. Before running, write a complete expected_drafts prediction for that edit; retain expected_input and all identity checks. Which source gains reviewed? Verify input preservation, both repeated original tags and source order. Then restore the original edit and prediction and rerun.
-
Explain why the slot replacement and alias rebinding in the trace do not undo the earlier mutation of original's tag list. If a colleague suggests comparing printed id integers or waiting for garbage collection to decide whether the tags are independent, identify the direct observations to use.
Answer and Reasoning
Hint 1: trace the last shared mutable edge
A new outer list says nothing about the identity of its dictionaries. A new dictionary says nothing about its tag list. Write the required identities before choosing the operation. Which containers can the later append reach?
Hint 2: keep the two isolation requirements separate
A deep copy can isolate a copied graph from its input while preserving sharing inside the copied graph. The editor additionally requires independent tag lists between drafts. Source order is unrelated to either identity requirement.
Compare your prediction
The deepcopy comparison passes the new outer/record/input-tag separation checks and fails draft records share tags. Its one memo maps the shared original tag list to one shared copied tag list. If edited, both drafts would see reviewed; the input would remain unchanged. The trace's final pair demonstrates that behavior directly. The targeted per-record list copy satisfies this editor's stronger rule without copying unrelated immutable values. A domain that requires shared tags between drafts could deliberately choose a different policy.
For the second variation, records/oak-a.json is still at index one and gains reviewed. The full replacement prediction is this data excerpt:
expected_drafts = [
{"source": "records/oak-b.json", "name": "Oak ledger", "tags": ["local", "local"]},
{"source": "records/oak-a.json", "name": "Oak ledger", "tags": ["local", "local", "reviewed"]},
]
The input retains two local tags in both records. The first draft also retains both, since its tag list is private. No sorting or deduplication belongs in this copy-only function. Restore the original edit and expected_drafts after comparing your result.
Replacing shallow's slot redirects that slot, and rebinding alias redirects
that name. Neither reverses the append already made through R1 to T1. Use is
on the relevant containers and compare the actual values before/after a chosen
mutation. Numeric id values can be reused after an object's lifetime and are
not a portable memory diagram. Do not infer independence from integer/string
literal identity, reference counts or garbage-collection timing. Do not use
garbage collection as resource cleanup; later lessons teach explicit ownership.
Deep copying is not a universal repair. Classes can customize copying, and external resources such as open files/sockets are not made independent working resources by this recipe. Immutable objects may be reused. This lesson's claims and repair are bounded to trusted built-in list/dict/string records; no custom copy hooks, concurrency safety or performance advantage is established.
Inspect and remove only this checkpoint
Programs create no output files or caches under -B. Inspect the exact saved root before cleanup:
cd "$AP_REFERENCES_ROOT" &&
test "$(cat .advanced-python-owner)" = 'advanced-python:lesson-4' &&
pwd &&
ls -la
Close editor files. If your editor created an extra backup, inspect it and remove only that explicitly named owned file; do not use a wildcard. After a partial setup, omit only source filenames you have confirmed were not created. Then remove the exact two scripts, marker and empty root:
cd "$AP_REFERENCES_ROOT" &&
test "$(cat .advanced-python-owner)" = 'advanced-python:lesson-4' &&
rm -- trace_references.py repair_boundary.py .advanced-python-owner &&
cd .. &&
rmdir "$AP_REFERENCES_ROOT" &&
unset AP_REFERENCES_ROOT AP_PYTHON
rmdir refuses a nonempty directory. Stop and inspect a refusal; do not replace this sequence with recursive deletion. Nothing here removes an earlier lesson's root, package environment or another person's files.
Sources and study views
The data model (S06) defines object identity/value/mutability; copy (S07) supports shallow/deep behavior, memo reuse and copying limits. Built-in list and dictionary operations (S63) support the specific container operations. The assert statement (S61) explains the enabled self-check boundary. Runtime and marked-root guards use the previously taught release baseline (S02), sys (S45), build/GIL distinction (S39) and pathlib (S16). These sources establish technical facts; all examples, predictions and artwork are original course material.
Revision reconstructs the decisions. Quick Reference retrieves the taught operations and commands. Return here for complete files, practice, answers and cleanup.