An object inspector examines references, identity and retained state to explain how a data structure is actually shared.
Audit repeated rows and object lifetime with checks that separate equal values from shared ownership.
The loader below runs without an exception, yet rows share defaults and retain their source in a cycle. Build a report before changing it. Combine three tools from this section: identity groups for shared fields, frozen value keys for duplicate rows, and weak probes for lifetime. Each report field must answer one specific question without altering the objects being inspected.

The loader's silent bug
A batch spec names a source, the raw rows, and defaults for any field a row is missing:
Row 0 got a tag, and so did row 2 — both took the default, and "the default" is
one list. Row 1 brought its own list, so it's unaffected. This is the mutable
default argument from lesson 02 and [[0] * 3] * 3 from lesson 01, in one more
disguise: one object, several names, a mutation.
defaults = {"tags": []}
rows = [{"id": i} for i in range(3)]
for r in rows:
r.setdefault("tags", defaults["tags"])
rows[0]["tags"].append("vip")
print(rows[2]["tags"], defaults["tags"])Preparing this topic’s interactive investigation…
Which rows repeat
Freezing each row's fields (lesson 02) turns "are these rows duplicates?" into a
set lookup. It compares values the way == does, which includes one quirk worth
re-meeting here:
def freeze(value):
if isinstance(value, list):
return tuple(freeze(v) for v in value)
if isinstance(value, dict):
return frozenset((k, freeze(v)) for k, v in value.items())
return value
keys = {freeze({"ok": 1}), freeze({"ok": True}), freeze({"ok": 1.0})}
print(len(keys))What survives the drop
Lesson 03's probes measure what's still alive after the batch is dropped. A
healthy loader gives 0 right after the drop. Quarry's gives rows + 1,
because every object in the batch is part of a row-source cycle:
Take away the batch bubble and every box still has an arrow coming into it,
which is why counting frees none of them. Step through the drop and watch the
two counts:
The measurement itself has a trap: any name still pointing at a row keeps it alive, including a leftover loop variable:
None of these rows are in a cycle, so the count after dropping batch should be 0. Run it, work out which row survived and why, then fix the drop.
The reliable fix is structural: do the loading and inspecting inside a helper that returns only the report and the probes. When the helper returns, its whole frame — the batch, every loop variable, every temporary — goes with it.
Three measurements, three different questions
Build the report in stages so one correct number cannot conceal another bug. Identity grouping asks which labels share a mutable object. Frozen-key grouping asks which rows compare equal. Weak probes ask which instances remain alive. None of these measurements substitutes for the others.
| Input situation | Shared-field report | Duplicate report |
|---|---|---|
Two rows separately contain tags: [] and equal IDs |
No shared list | Equal rows |
| Two different IDs take the same default list | Shared tags |
Different rows |
| A row contains two references to one nested object | Possibly beyond this inspector's field-level view | Depends on field values |
The last row is a deliberate limit: this inspector groups direct list/dict field values, not every nested reference in an arbitrary object graph. A clean report means the stated checks passed; it does not establish complete isolation.
During look, keep the batch alive while grouping by id. Return only labels,
counts and weak probes. After look returns, measure before collection and after
collection. Counting first and deleting later would measure your own local
ownership instead of the loader's graph. The empty batch is a separate boundary:
there is no row from which to recover a source.
Before implementing, sketch the expected report for two equal rows with separate lists, then two unequal rows sharing a default. After implementing, mutate one shared default and inspect again. Identity groups should persist while equality groups may change. That is a useful independent check of what each field means.
What the report is for
A report doesn't fix anything, but it names the fix precisely:
- Shared fields → copy the default per row.
Check
if key not in fields, then assigncopy.deepcopy(value). Copy only when needed; arguments tosetdefaultare evaluated even when a key exists. - Rows alive after the drop → give the cycle an owner. Rows hold their
source strongly; the source tracks its rows weakly, with a
weakref.WeakSet. Lesson 03's rule: strong references run in the direction of ownership. - Duplicates → dedupe with frozen keys, lesson 02, before rows go anywhere else.
Quick practice
Calling probe_all and letting it return is enough — nothing outside keeps
objs alive, so every row is already gone by the time the function hands the
probes back.
🎯 Your turn
The starter gives you Source, Row, load_batch and freeze, exactly as
above. Write inspect_batch(spec), returning:
"rows"— how many rows were loaded"shared"— groups of"<row>.<field>"labels whose values are the samelist/dictobject (sorted labels, sorted groups)"duplicates"— groups of row indices whosefieldsare equal (two or more, first-seen order)"alive_after_drop"— how many rows + source survive dropping the batch, with the collector off"alive_after_collect"— the same count aftergc.collect()
For the orders.csv spec above:
{"rows": 3, "shared": [["0.tags", "2.tags"]], "duplicates": [], "alive_after_drop": 4, "alive_after_collect": 0}.
Hint: a helper look(spec) loads the batch, builds the report and the
probes, and returns just those two — its own frame going away is what keeps the
measurement honest. inspect_batch disables the collector, calls it, counts,
collects, counts again, and re-enables the collector in a finally.
Press ▶ Run, then ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write load_fixed(spec), a loader that gives every row its OWN copy of each default it takes, instead of the shared object. distinct_defaults(n) (given) loads n rows that all take the defaults tags: [] and meta: {}, and returns [distinct tag lists, distinct meta dicts], counted by identity.
Write duplicate_groups(rows). Each row is a JSON dict, possibly nested. Return the groups of row indices whose rows are equal, keeping only groups of two or more, in the order each group first appears.
Write shared_labels(spec). Load the batch with the given load_batch, then group the labels "<row>.<field>" by the identity of each field's value, counting only list and dict values. Return the groups of two or more labels, each group sorted, and the groups sorted.
Change Source and Row so that there's no cycle: the rows keep a strong reference to their source, and the source tracks its rows WEAKLY, so it can still say how many live rows it has. drop_report(n) (given) builds a source with n rows, records how many rows the source sees, drops everything with the collector off, and counts what's still alive.
Write load_safe(spec) and fix the model so that the inspector's report comes back clean. Every row gets its own copy of each default, and the source tracks its rows weakly while the rows own the source. safe_report(spec) (given) returns rows, shared, source_sees (how many rows the source can see) and alive_after_drop, which must be 0.
The inspector reports alive_after_drop: 4 and alive_after_collect: 0 for a three-row batch. A teammate says: "Zero after collect, so there's no leak. Ship it." Are they right? Explain what the two numbers mean and what it would cost Quarry to leave this as it is.