Lesson · Copying, Memory & Object Lifecycle
Reference Counting & Garbage Collection
90 min readReference Counting & Garbage Collection
CPython primarily uses reference counting plus a cyclic garbage collector. Understanding the distinction between language guarantees and CPython details prevents incorrect lifetime assumptions.
Learning goals
- Trace how a reference count changes as names are bound, linked, and deleted.
- Explain why two objects that reference each other survive
deland are freed later by the cyclic collector. - Read
sys.getrefcountoutput while accounting for the temporary reference the call itself creates. - Say which parts of the behavior are CPython implementation details and which are language guarantees.
- Explain why resource cleanup belongs in a context manager rather than a finalizer.
Mental model
The first two lines are CPython's main path, and the third is why the gc module exists at all. Program logic should depend on reachability, never on the exact moment either mechanism runs.
Counts handle the chain, reachability handles the cycle
counting is CPython; reachability is the contract
Mental model
the same mechanism as a compact list
strong reference created → count +1 strong reference dropped → count -1 (0 means reclaim now, in CPython) unreachable cycle → counts stay positive, cyclic collector reclaims it
Core idea
CPython frees an object the moment its last strong reference disappears, which is prompt and convenient, but that timing is an implementation detail rather than a language promise. Cycles defeat plain counting, so a separate collector finds groups of objects that reference only each other and reclaims them. Well-written code treats deallocation time as unknown and releases resources explicitly.
Object references
A Python-level reference is a connection from a name, container slot, attribute, frame, or other object to another object. Object lifetime depends on the complete reference graph.
CPython reference counting
CPython increments and decrements reference counts as references are created and removed. Many objects are reclaimed promptly when the count reaches zero, but this timing is not a portable language guarantee.
Cycles
Reference counting alone cannot reclaim a cycle whose objects reference one another. CPython's cyclic garbage collector detects many unreachable cycles separately.
Cyclic garbage collector
Because reference counting cannot free a cycle, CPython runs a separate collector that tracks container objects and reclaims groups reachable only from one another. gc.collect() runs a collection on demand and returns the number of unreachable objects found, which is why the count can include leftover garbage from anywhere in the process.
Object destruction
Object destruction timing is implementation-dependent. In CPython, reference counts often make destruction prompt, but cycles and other Python implementations mean code should not rely on that timing.
__del__ caveats
__del__ is a finalizer hook with subtle lifetime and shutdown behavior. Use context managers for deterministic resource release instead of relying on finalization.
Walkthrough
a = Node()andb = Node()bind two instances, anda.other = bwithb.other = alinks them into a cycle, so each object is reachable from the other.sys.getrefcount(a)returns the true count plus one temporary reference created by the call itself, which is why the number is never the intuitive one.del a, bremoves the names but not the internal links, so the counts fall to one apiece and counting alone reclaims nothing; the two objects become an unreachable cycle.- Predict before running: whether anything is freed by the
delline, and how the collector's return value changes when the twootherassignments are removed.
Experiments to try
- Remove the two
otherassignments and rerun; the counts now hit zero ondel, and the collector's return value no longer has to cover the nodes. - Keep an extra name (
alias = a) and printsys.getrefcount(a)before and afterdel alias; explain each change with the strong-reference rule. - Break the cycle with
a.other = Nonebefore deleting the names; the objects are freed by counting alone, and the collector finds nothing from this structure. - Print
gc.is_tracked(a)for the node and for an integer; the node is tracked by the collector while the small integer is not, which shows what "container" means for the cyclic collector.
Playable lesson
Lab: Reference counting and GC
Add and remove reference edges, create a cycle, and run collection. Label CPython-specific behavior explicitly.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Reference counting and GC
Objects and edges
- node Acount 1
held by name a
reachable
Reachable
A
from a live frame
Total count
1
no stranded objects
Predict first
How many references does `a` hold to the object after this line?
Creating a node binds it to a name, and a name is a strong reference. In CPython the count is not bookkeeping you manage: it changes with every reference created or dropped.
Common mistakes
- Treating prompt CPython destruction as a language guarantee: other implementations may collect later or differently, so code should not encode the timing into program logic.
- Reading
sys.getrefcount(x)as the exact count: the call adds a temporary reference, and other inspectors can add more, so subtract before interpreting the number. - Using
__del__to release critical resources: finalizers can be delayed by cycles or skipped during interpreter shutdown, while context managers release deterministically. - Expecting an unreachable cycle to be freed the moment the last name disappears: counting cannot do it, and the collector runs periodically or on demand, so lifetime is unbounded until
gc.collect().
Practice: Easy
- Run the worked example and explain the three printed lines using references and the collector; then add a
printofgc.collect()before thedeland compare the two calls. - Delete only one name (
del a) and inspect the other node'sotherattribute; the object survives through the internal link. - Replace the cycle with a chain (
a.other = bonly, no link back) and rerun; confirm that deleting the names frees both objects by counting alone.
Practice: Medium
- Track counts through a small script: print
sys.getrefcount(a)after creation, after linking, and afterdel b, and mark which change each count corresponds to. - Build a temporary cycle inside a function (two locals referencing each other) and call
gc.collect()after the call returns; separate what counting would reclaim from what needs the collector. - Compare
delsemantics for a name and for a list entry: remove the last reference through each route and show when the object is reclaimed.
Practice: Hard
- Build a graph with a cycle plus an external reference, then drop the external reference and one internal edge in different orders; chart when counting frees objects and when the collector must run.
- Set up a failure lab with three broken expectations: a
__del__finalizer that raises, a cycle expected to die atdel, and agetrefcountreading misread by one; explain each symptom from the lifetime model. - Design a class that holds a resource and whose cleanup must run even if users forget to do it; choose between a context manager and
__del__, and justify the choice with timing guarantees.
Lesson checklist
- I can trace a reference count through bindings, deletions, and an internal link, allowing for inspection overhead.
- I can explain why a cycle survives
deland how the collector finds it. - I can state which parts of the behavior are CPython details and which are language guarantees.
- I can say why resource cleanup belongs in a context manager rather than a finalizer.
Remember
CPython frees objects when their last reference goes away, and a separate collector handles cycles that counting cannot see; neither timing is a language guarantee, so portable code reasons about reachability instead of destruction moments. `gc.collect()` forces a collection, `sys.getrefcount` exposes one inspector's view, and context managers stay the right home for cleanup.
Interview angles
What is the main purpose of **Object references**?+
A Python-level reference is a connection from a name, container slot, attribute, frame, or other object to another object. Object lifetime depends on the complete reference graph.
What should you pay attention to when using **CPython reference counting**?+
CPython increments and decrements reference counts as references are created and removed. Many objects are reclaimed promptly when the count reaches zero, but this timing is not a portable language guarantee.
How does **Cycles** fit into this lesson?+
Reference counting alone cannot reclaim a cycle whose objects reference one another. CPython's cyclic garbage collector detects many unreachable cycles separately.
Why can a cycle keep two objects alive after `del` removes every name that pointed at them?+
Each object still holds a strong reference from the other, so no count ever reaches zero. The pair is unreachable from the program but remains countable on paper, which is exactly the case the cyclic collector exists to reclaim.