An object’s lifetime is the period during which it exists. Garbage collection reclaims objects that are no longer needed or reachable.
Track strong ownership, weak references and cycles, and distinguish deleting a name from destroying an object.
Deleting a name does not necessarily release the object it reached. Follow the remaining references to find what keeps a batch alive. You will use weak probes to observe that lifetime, then separate retained objects from unreachable cycles. The immediate-release demonstrations describe CPython behaviour, not a language promise about when every Python implementation reclaims memory.

An object is reachable while some chain of strong references leads to it from a root — a running function's local variables, or a loaded module's globals. Here's that idea for a batch of rows and a cycle of nodes at once. Step through it:
An object lives while a chain of references leads to it from a root. Reference counting frees most garbage the moment it's cut loose, but not a cycle.
The roots: the running function's local variables, and the module's globals. 8 nodes, 8 edges, directed. Settled: frame locals, module globals.
The last two steps are the whole story of this lesson. In these CPython examples, acyclic objects are usually released promptly. Unreachable cycles need the additional collector; reclamation timing is not a language-level guarantee.
del removes a name, not an object
To watch an object actually die, you need a way to point at it that doesn't count as a reference — otherwise watching it would keep it alive. That's a weak reference:
A weak reference only reports the death. It says nothing about why an object stayed alive — that depends entirely on what else still points at it.
Preparing this topic’s interactive investigation…
Observe lifetime without becoming an owner
The earlier aliasing rules still apply to a diagnostic tool. Saving an object in
a variable to inspect it adds another strong reference. A weak probe avoids that
until you call it: held = probe() creates a normal strong reference again.
On the reference-counted CPython runtime used by these examples, this prints
True then True. The first observation did not contradict del; held was
still an owner. Debugger frames, exception tracebacks, registries, and cached
results can all create less obvious paths of the same kind.
Use the graph to ask two separate questions: “Can running code still reach it?” and “Has the runtime reclaimed it yet?” Unreachable cycles may await collection. Reclaimed Python objects also need not immediately reduce the process's operating system memory reading; allocators can retain space for reuse. A high memory graph alone does not identify the cause.
For a resource that must close at a known point, use with or explicit cleanup,
not collection timing. For the cycle exercises, restore the previous
gc.isenabled() state in finally, and release diagnostic locals before counting.
Try retaining one row deliberately: predict which other objects its references
keep alive after collection. That distinguishes a reachable graph from garbage.
A registry that quietly leaks
A module-level dict that remembers "batches currently in use" sounds harmless. It's Quarry's actual overnight leak:
The registry should let you look batches up without keeping any of them alive forever. Run it, notice the batch survives del, then change one line.
A WeakValueDictionary drops an entry automatically the moment its value dies
everywhere else — exactly the shape a "look up what's still in use" registry
needs. A plain dict, a module-level list, or a closure that captured an object by
accident all leak the same way: not because Python forgot to free something, but
because something still, technically, reaches it.
Two nodes that can't free each other
For the ordinary CPython objects here, reference counting usually releases an object when its last strong reference disappears. Two objects that point at each other break that, because neither count ever reaches zero on its own:
import gc
import weakref
gc.disable() # keep the cycle collector out of it, for now
class Node:
pass
x = Node()
y = Node()
x.other = y
y.other = x
probe = weakref.ref(x)
del x, y
before = probe() is not None
gc.collect()
after = probe() is not None
print(before, after)
gc.enable()Step through the same code, and watch probe. Its display changes to dead
only after the collector runs:
The collector tracks objects that may participate in cycles, including user
instances; it can optimise tracking of some containers. gc.is_tracked([]) is
True and gc.is_tracked(1) is False in these examples. gc.collect()
requests collection even when automatic collection has been disabled. Do not
rely on an exact automatic schedule: it is runtime- and version-dependent.
One-liner: weak back-references break the cycle on purpose
A tree where every child points back at its parent is a cycle at every level. The standard fix: decide which side owns, and make the other direction weak.
Quick practice
import weakref
class Batch:
pass
a = Batch()
b = a
probe = weakref.ref(a)
del a
print(probe() is None)gc.get_referents(obj) exposes references visited by the runtime's traversal
support. It is a diagnostic view, not a guaranteed inventory of every object
reference. The exercise deliberately restricts the graph and object types.
🎯 Your turn
Write find_cycles(links, roots). links maps each object's name to the names
it refers to, e.g. {"a": ["b"], "b": ["a"], "c": []}. Build a real object for
each name, wire up the references, keep strong references only to the names in
roots, then let go of everything else and report:
"freed_at_once"— names already dead before any collection (reference counting alone got them)"cycle_garbage"— names still alive untilgc.collect()runs"alive"— names still alive afterwards (reachable from a root)
Each list sorted. find_cycles({"a": ["b"], "b": ["a"], "c": []}, []) →
{"freed_at_once": ["c"], "cycle_garbage": ["a", "b"], "alive": []}.
Hint: keep the collector disabled while you build and check, so it can't run early and blur the first two lists — re-enable it before you return. Build inside a helper function so its locals (including any leftover loop variable) go out of scope when it returns.
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 survives(holders). Make one Batch, then for each entry in holders store it one more way, keeping every holder in a local list: "list" means [batch], "dict" means {"k": batch}, and "weak" means weakref.ref(batch). Delete the original name and return whether the batch is still alive, checking with a weak probe.
Write live_after(names, keep). Load a Batch for each name into a registry, holding a strong reference only to those whose name is in keep. Return the sorted names still in the registry. The starter's registry is a plain dict, so nothing is ever freed, and even a weak registry has one more trap: the loop variable.
Quarry's yard is a tree of Folders. Each folder keeps its children and can report its parent, but with a strong parent attribute every parent-child pair is a cycle, and dropping the root frees nothing until the collector runs. Change Folder so the parent is held weakly, while folder.parent still returns the parent folder (or None). drop_chain(depth) (given) builds a chain, drops it with the collector switched off, and reports what's left.
Write reachable(links, roots): build an Obj for every name and wire up its refs, then find every Obj reachable from the root objects by following gc.get_referents itself, the same view the collector has. Don't read obj.refs directly. Follow only referents that are Obj, list or dict instances (an instance's references pass through its attribute storage). Return the sorted names reached.
Write cache_session(ops), a session against Quarry's batch cache. Each op is ["load", name] (make a batch, cache it, and hold it strongly), ["link", a, b] (set a's partner to b), ["drop", name] (stop holding it), ["collect"] (run the collector) or ["get", name] (record "hit" if the cache still has that batch, else "miss"). The cache must never keep a batch alive by itself. Return the list of get results. The collector stays off except during collect.
Explain why CPython uses reference counting AND a cycle collector, rather than just one of them. What does each do well, what can't counting handle, and what does that mean for how you design a class with back-references?