The second mechanism — the one that finishes the job after the count. From it you can derive why __del__ is unreliable, why turning the collector off sometimes makes code nine times faster, and why the memory you freed did not go back to the operating system.
import gc
class Node:
def __init__(self, n): self.n = n; self.peer = None
def __del__(self): print(f"deleted {self.n}")
a = Node(1); b = Node(2)
a.peer = b; b.peer = a
del a, b
print("after del")
print("collect returned:", gc.collect())
after del
deleted 1
deleted 2
collect returned: 2The destructors were called after all — but not when the objects became unreachable.import gc
print(gc.get_threshold())
print(gc.get_count())
(700, 10, 10)
(13, 0, 0)Three numbers and three numbers. What exactly is being counted, and why are the thresholds so different?xs = [[i] for i in range(2_000_000)] # took up memory
del xs[::2] # deleted half, every other one
gc.collect()
# how much memory came back to the process?
peak 238 MB
after 232 MBA million objects out of two were deleted — six megabytes were freed.import gc, time
def build():
t = time.perf_counter()
data = [{"i": i, "p": None} for i in range(1_500_000)]
return time.perf_counter() - t
gc.enable(); print(build())
gc.disable(); print(build())
2.10
0.23One line of configuration — the code is nine times faster. And not a single object here forms a cycle.The previous lesson ended on a hole: the count is local and knows nothing about reachability, so to it a cycle of references is indistinguishable from a live object. So a mechanism that works with reachability is needed. It exists, and it is built minimally — exactly enough to close that hole and not a step more.
The collector tracks only containers — objects that are capable in principle of referring to others. A number, a string, bytes are not tracked at all: they cannot take part in a cycle.
It looks for groups reachable only from inside themselves. For each tracked object its count is taken, and the references coming from other objects in the group are subtracted. A remainder above zero means something outside is looking at the object, and it is alive together with everything it reaches. A zero remainder for the whole group means the group is garbage.
It divides objects into three generations. A new object goes into generation zero; one that survives a collection moves to the next. Generation zero is checked often, generation two rarely.
Snippet A. At the moment of del a, b nothing happens: the counts of both nodes are one, held by the neighbour. The objects become garbage, but nobody knows it. The knowledge appears only when the collector goes through generation zero — on schedule or on an explicit gc.collect().
Hence the main practical conclusion about __del__: the moment it is called is undefined if the object takes part in a cycle. And it does so often and unnoticed — a parent with a list of children, each child with a reference to the parent; a closure that captured the object that stores it; an exception whose traceback refers to the frame in which the exception itself lives.
A historical detail that explains other people's advice: before 3.4 the collector flatly refused to collect cycles containing an object with __del__ — it could not choose a finalization order and put such groups into gc.garbage, that is, into an eternal leak. PEP 442 fixed that, and today cycles with destructors are collected normally. But the rule “do not rely on __del__” outlived its reason and remained true for another reason — this one.
Snippet B: (700, 10, 10) is not “every 700 objects”. The first number is the excess of objects created over objects destroyed at which a pass over generation zero is triggered. The second and third are how many collections of the younger generation must happen before the next one is traversed.
What follows is the arithmetic that explains snippet D. While the code in the loop creates a million and a half dictionaries and deletes nothing, the “created minus deleted” difference grows continuously. Every seven hundred objects a pass over generation zero is triggered; every ten such passes, one over generation one; every ten of those, one over generation two. And a pass over generation two is a walk over all live tracked objects, of which there are already a million by then.
The result is a pathology: the more long-lived objects the program has accumulated, the more expensive each full collection is, and it is triggered precisely in the phase when objects are being created actively. The ninefold difference in the measurement is this.
| 1.5M dictionaries | time |
|---|---|
| collector on | 2.10 s |
| collector off | 0.23 s |
Note that there are no cycles in this code at all. The program pays for a mechanism it does not use — and that is not an implementation mistake but an inevitability: the only way to find out whether there are cycles is to walk the objects.
Snippet C is about the third level, the allocator. Python does not go to the operating system for every object. It takes large pieces from it — arenas — cuts them into pools of equal size, and pools into blocks by size class with a step of eight bytes. An object below a threshold of half a kilobyte gets a block; anything larger goes straight to the system malloc.
When an object dies, its block returns to the pool and is immediately available for the next object of the same size. Nothing is returned to the operating system. An arena is given back only when it becomes completely empty.
Now snippet C is obvious: we deleted every other object, so half of the live ones remained in every arena. Not one arena emptied, not one was returned — RSS dropped by six megabytes out of two hundred and thirty-eight. This is fragmentation, and it is observed in any long-lived process.
Hence an important consequence for reading metrics: RSS is not a measure of a leak. Memory that did not drop after a clean-up can mean a leak or ordinary fragmentation, and those are two different diagnoses with different treatments.
Since the problem is that a reference retains an object, a way to refer without retaining is needed. weakref is exactly that: a pointer that does not increase the count. The object dies by its own rules; after that the weak reference returns None, and, if asked, calls a callback at the moment of death.
The right uses follow from this: registries, observers, caches, “child → parent” back references. Everything that should know about an object but should not decide when it dies.
Not everything is tracked. A tuple consisting only of immutable atomic objects is eventually taken off tracking — it cannot take part in a cycle. That is why gc.get_referrers will not show some paths, and there are always fewer “objects in gc.get_objects()” than objects in the process.
Turning the collector off is not a free accelerator. It is correct only where cycles are known not to form, or where the phase is followed by an explicit gc.collect(). In a web application with an ORM cycles form constantly, and a disabled collector turns into a slow leak.
Finalization at interpreter shutdown is undefined 🕳. The order of destruction on exit is not guaranteed, some objects may not be finalized at all, and by that time modules are already partly dismantled — which is why a __del__ that touches global names sometimes fails on exit with mysterious AttributeErrors.
The numbers of generations and thresholds are an implementation detail 🔧. In 3.12 the generation scheme was reworked; the idea “the young are checked more often” remained, the specific figures did not.
The root is the same as in the previous lesson: lifetime is governed by a reference count. Everything discussed here is not an independent decision but a patch on a known defect of the count, and it is important to understand that.
The cycle collector appeared in Python 2.0, ten years after the language itself. For ten years cyclic references simply leaked. When it was added, the key requirement was compatibility: thousands of existing C extensions manipulated the count directly and knew nothing about any graph traversal. So the collector was made an add-on — it does not replace the count and does not touch objects it was not told about.
Hence an honest assessment of the price: Python pays for both schemes at once. For the count — with operations every time an object is passed and with a global lock. For the collector — with periodic walks over all live objects. Languages with tracing collection pay only for the second half.
If you have worked with PyTorch on a GPU, the allocator's design is already familiar. The CUDA caching allocator takes large blocks from the driver, cuts them for tensors and does not return them to the driver when a tensor is freed. That is exactly why nvidia-smi shows memory in use after everything has been deleted, and exactly why torch.cuda.empty_cache() exists.
It is the same technique and the same problem: talking to the system is expensive, so memory is cached in pools; a pool is given back only when it is empty; with an unlucky layout of live blocks nothing is given back. The only difference is that PyTorch has a button for forced return and CPython does not — an arena is freed by itself or not at all.
Questions that come up on their own if you read closely. The answer is under the question.
Because “free an object” and “return memory to the OS” are two different events, and the second happens far more rarely.
CPython allocates memory in arenas of 1 MB (in 3.11 — 1 MB, earlier 256 KB), cuts them into pools, and pools into blocks for small objects. An arena is returned to the system only when it is completely empty. One live object in an arena retains the whole megabyte.
import gc
big = [object() for _ in range(1_000_000)]
del big[1:] # exactly one object left
gc.collect()
# RSS will hardly change: the live objects are scattered across arenas
This is classic fragmentation, and it is not a bug: the alternative is to move objects, and they cannot be moved, because C extensions hold raw pointers to them (lesson 15). A compacting collector as in Java is impossible here for the same reason the GIL cannot be removed.
What follows in practice. A growing RSS does not prove a leak, and a stable one does not prove its absence. What should be measured is not RSS but the number and types of live objects — tracemalloc, gc.get_objects(), snapshots before and after. And if the memory peak is a one-off (loaded, processed, threw away), the most reliable way to return memory to the system is to do the work in a separate process and let it exit.
Because checking everything is a stop-the-world pause proportional to the number of live objects, and an average process has millions of them.
At the base is an empirical observation that holds in almost every language: the overwhelming majority of objects die young. A temporary list inside a function, a string from formatting, an argument tuple. Long-lived ones — the config, caches, modules — are few, and checking them at the same frequency is pointless.
Hence three generations and the thresholds (700, 10, 10): generation zero is checked after every 700 “excess” allocations, generation one after every ten passes over zero, generation two after ten passes over one. An object that survives a check is promoted.
import gc
print(gc.get_threshold()) # → (700, 10, 10)
print(gc.get_count()) # current counters
print(gc.get_stats()[2]) # what the oldest generation has been doing
The practical consequence that makes this worth knowing: a bulk load of data into memory creates hundreds of thousands of long-lived objects, and every pass over the oldest generation walks all of them — for nothing, because they are alive. A measurement from this lesson: gc.disable() for the duration of the load gave a ninefold speed-up.
The scheme was reworked in 3.12: the idea “the young are checked more often” remained, the specific thresholds did not 🔧.
gc.disable() — when is it safe?When you understand what exactly you are turning off: not garbage collection, only the search for cycles.
The reference count keeps working always; it cannot be turned off. gc.disable() stops only the periodic generation passes — so everything that is not in cycles is freed as usual, and immediately.
Safe: for the duration of a phase that creates many long-lived objects without cycles — loading a dataset, parsing a big file, warming a cache. The classic technique:
import gc
gc.disable()
try:
data = load_everything() # hundreds of thousands of objects
finally:
gc.enable()
gc.collect() # one honest collection
Dangerous: permanently, in a service. Cycles form far more often than it seems: any parent ↔ child, any exception whose traceback refers to a frame, any object with a callback method on itself. Without the passes they will never be freed, and memory will grow monotonically.
An intermediate option that is often better than both: leave the collector on but raise the thresholds — gc.set_threshold(50_000, 20, 20). The passes become rare but do not disappear. One more technique, for fork servers, is gc.freeze() after loading: it moves the current objects into a permanent generation, and they stop taking part in passes altogether.
__del__ considered unreliable if the count works?Because it has four different ways not to fire, and three of them do not depend on the programmer.
First — the moment is not guaranteed. An object in a cycle will die not when the reference is lost but at the next generation pass. When that will be is unknown.
Second — interpreter exit. At shutdown modules are dismantled, globals are cleared, and __del__ may not be called at all, and if it is, it will find that the names it needs are already None 🕳.
Third — exceptions are swallowed. An error inside __del__ does not propagate: it is printed to stderr and execution continues, because there is nowhere to raise it from — there is no calling context.
class T:
def __del__(self): raise ValueError("an important error")
t = T(); del t
print("the program goes on")
# → a message in stderr, the exception is lost
Fourth — resurrection. __del__ can store self somewhere, and the object comes back to life. Since 3.4 (PEP 442) a finalizer is called at most once per object, and there will be no second death.
What to use instead. with — when the resource's lifetime is visible in the code. weakref.finalize — when it is not: it is called more reliably, is registered explicitly and does not retain the object. atexit — for process-level resources. __del__ is worth keeping only as a last line of defence with a warning in the log: “this object was not closed through with”.
__del__ is unreliable; a collection costs time proportional to the number of live objects, so in a phase of mass creation turning the collector off gives a ninefold speed-up; freeing an object and returning memory to the system are different events, so an RSS that did not drop is not proof of a leak. Python pays for both memory-management schemes at once — the price of deterministic destruction and of compatibility with an ecosystem that would not have arisen without it.
Java uses generations as the main mechanism, not as an add-on. The hypothesis is the same — most objects die young — but everything has been squeezed out of it: a copying collector for the young generation makes allocation almost free, and compaction solves the fragmentation problem, for which Python has no solution at all. The price is pauses and not being able to know the moment of destruction.
Go chose a concurrent collector focused on short pauses and paid with throughput. Rust gave up collection altogether: ownership is checked by the compiler, and cycles require Rc with Weak by hand — the same problem, again put on the programmer, as in Swift.
The general conclusion: there is no mechanism without a price, and Python is the only one of those listed that pays twice. In return it got deterministic destruction and compatibility with a giant ecosystem of C extensions that simply would not have arisen without this decision.
“We have a leak: we cleared half the cache and the memory did not come back.” There is no leak.
xs = [[i] for i in range(2_000_000)]
del xs[::2] # threw away half the records
gc.collect()
| moment | RSS |
|---|---|
| start | 8 MB |
| peak | 238 MB |
| after deleting half | 232 MB |
| after deleting everything | 11 MB |
A million objects out of two million were freed, and RSS dropped by six megabytes. It looks like a leak exactly until you delete everything — and then the memory comes back almost entirely. So the objects were being collected normally, and the issue is the arenas: half of the live objects remained in each, and not one emptied.
Why this is dangerous: a team that sees such a graph starts hunting a leak that does not exist, adds gc.collect() to the hot path (which does not help — the collector is not in the business of returning memory to the system) and ends up restarting workers on a timer. The real cure is different: do not delete at scattered positions from a long-lived structure but re-create it as a whole, or keep homogeneous data outside the object model — in an array, a buffer or numpy, where a million numbers lie in one piece.
Telling one from the other is simple: a tracemalloc snapshot before and after will show whether the number of live objects is growing. Growing — a leak. Not growing, with a high RSS — fragmentation.
A phase of bulk data loading is sped up by turning the collector off — but only if you understand what you are paying for.
import gc
gc.disable()
records = load_everything() # millions of objects, nothing is deleted
gc.enable()
gc.collect() # once, deliberately
| 1.5M objects | time |
|---|---|
| collector on | 2.10 s |
| collector off | 0.23 s |
The ninefold gain comes from consequence 2: in a phase where objects are only created, the “created minus deleted” difference grows continuously, passes are triggered constantly, and each one is more expensive than the last because there are more and more live objects. The collector is looking for cycles that are not there — and the more successfully the load goes, the harder it looks.
When it is legitimate. The phase is bounded in time; it mostly creates rather than deletes; it is followed by an explicit collect. Loading a dataset, parsing a big file, warming a cache at startup.
When it is shooting yourself in the foot. A long-lived request handler, an ORM, any code where objects are created, die and refer to one another. There a disabled collector is a slowly growing leak that will be noticed a week later.
A related technique for forking servers is gc.freeze() before the fork: it does not turn collection off but takes out from under it everything that is known to outlive the process. Cheaper and safer than turning it off completely.
Run the four snippets and check them against your prediction. Then:
import gc
class A:
def __init__(self): self.me = self
for _ in range(100_000): A()
gc.collect()
# How many will it return? And if you remove self.me?
try:
raise ValueError("x")
except ValueError as e:
pass
# Why does Python itself delete the name e after the except block?
# Which cycle does it break by doing so?
t = (1, 2, 3)
gc.is_tracked(t)
t2 = (1, [2], 3)
gc.is_tracked(t2)
# Why are the answers different, and what does that save?
The second question is the most elegant one: the deletion of e after except is written into the language on purpose 🔒, and the reason is exactly the mechanism of this lesson.
The gc module in other people's code is the best way to see who actually touches the collector and why. Search for gc.freeze(): it appeared in 3.7 on a specific request and solves a specific problem. A web application loads all its code and data and then forks into workers. Under copy-on-write the pages should stay shared — but the collector, walking the objects, touches their headers, the pages become private, and memory consumption grows linearly with the number of workers. gc.freeze() moves everything created before the fork into an untouchable generation.
Note the shape of this solution: it is not an optimization of the collector but a way to switch it off for specific objects — because the mechanism is unable to tell “data that lives forever” from “garbage” automatically.
The second place is Lib/weakref.py, the WeakValueDictionary class. Notice how it is built: the values are stored not directly but wrapped in weak references with a callback that removes the entry when the object dies. The self-cleaning cache from consequence 4, ready-made.
From L1 you know that the collector looks for groups reachable only from inside. Here: exactly how, and what can be measured.
The algorithm fits into four steps. For the generation being collected, each object gets a temporary copy of its count. Then the collector walks all objects of the generation and asks each for its references — the type has a traversal slot, tp_traverse, for this — and for every reference to an object inside the same generation it decrements the target's temporary count. After the walk the temporary count shows the number of references from outside. Everything with a count above zero is a root; a depth-first search runs from the roots and everything reachable is marked alive. What remains unmarked is cyclic garbage; it is finalized and freed.
This shows why the collector works only with containers: if a type has no tp_traverse, it is invisible to the walk. And why writing a correct C extension with a container is hard: a forgotten tp_traverse gives not a crash but a silent leak of cycles.
What you can look at:
print(gc.get_stats()[2]) # statistics for the oldest generation
# → {'collections': 3, 'collected': 118, 'uncollectable': 0}
gc.set_debug(gc.DEBUG_STATS) # print the time of every collection
len(gc.get_objects()) # how many objects are tracked
collections for the oldest generation is the most useful metric: if it grows on the hot path, the collector is regularly walking all live objects, and it is worth looking at the thresholds through gc.set_threshold. The practice for services with a large permanent set of objects is to raise the first threshold several times over: full passes become rarer and find exactly as much.
Two things are measurable about the allocator from consequence 3: sys._debugmallocstats() prints the layout by size class and the number of arenas, and the difference between the tracemalloc total and the process RSS is that very fragmentation plus overhead.
Tag v3.11.15.
Modules/gcmodule.c, function subtract_refs — those very subtractions of internal references, step by step. Then move_unreachable — the split into the living and the garbage.Objects/obmalloc.c — the whole allocator. At the top of the file is a large comment with a map of arenas, pools and blocks; it is better than any retelling, this one included.__del__ were an eternal leak.Objects/typeobject.c, search for tp_traverse — how a type tells the collector about its references.Rc with Weak in Rust and ARC in Swift: there is no second mechanism, cycles are the programmer's jobtp_traverse, and why writing a correct container in C is harddict itself is built, whose layout determines most allocations — in L05main, so it already describes the post-3.12 generation scheme — the mismatch with the numbers in this chapter is expected and telling in itself.gc documentation — selectively: freeze, get_stats, set_threshold. The rest is reference material.