Sub topic 14
Inspecting and tuning the garbage collector
This chapter assumes you know that reference counting frees most objects at once and that the cyclic collector handles reference cycles. It also assumes you know what a weak reference is. Here you will look inside the collector, measure what it costs, and learn when changing its settings is justified. Most programs never need to change them.
What the collector tracks
The cyclic collector only looks at container objects: lists, dicts, instances of classes, and other objects that can hold references to other objects. Integers, floats, and strings cannot take part in a cycle, so the collector ignores them. CPython also stops tracking some containers it can prove are harmless, such as tuples that contain only untracked objects.
The collector sorts tracked objects into generations. A new object starts in generation 0. If it survives a collection of its generation, it moves to the next older one. The idea is that most objects die young, so collecting the youngest generation often is cheap. Collecting the oldest generation is expensive, so it happens rarely.
Reading the current state
The gc module exposes the collector's settings and counters.
import gc
print(gc.isenabled()) # True unless someone called gc.disable()
print(gc.get_threshold()) # commonly (700, 10, 10); check your version
print(gc.get_count()) # current counters, for example (143, 4, 2)
for generation, stats in enumerate(gc.get_stats()):
print(generation, stats)get_threshold()returns the three trigger values.get_count()returns the current counters. The first number is container allocations minus deallocations since the last generation 0 collection. The second and third count how many collections of the next-younger generation have run since the last collection of that generation.get_stats()returns one dictionary per generation withcollections,collected, anduncollectable.
The default thresholds differ between CPython versions. Python 3.14 reworked the collector to collect the old generation incrementally, and its defaults are not the classic (700, 10, 10). Always print gc.get_threshold() on the interpreter you deploy to instead of assuming a value.
The counter is net allocations, not total allocations. A loop that creates and frees a list on each pass leaves count0 close to where it started, so it does not trigger collections.
Forcing a collection and reading the result
gc.collect() runs a full collection by default and returns the number of unreachable objects it found. You can pass a generation, gc.collect(0), gc.collect(1), or gc.collect(2), to collect only that generation and the younger ones.
import gc
class Node:
def __init__(self):
self.other = None
gc.collect() # start from a clean slate
a, b = Node(), Node()
a.other, b.other = b, a
del a, b
found = gc.collect()
print(found >= 2) # True: at least the two Node objects were unreachableThe exact number varies by version. Older versions also count each instance's __dict__, and newer ones often do not create that dictionary. Do not write tests that depend on the exact value. Test that it is larger than zero, or use a weak reference as in the earlier cycles chapter.
Measuring collection cost with callbacks
Before changing any setting, find out whether the collector is a problem. gc.callbacks is a list of functions that the interpreter calls before and after every collection. Each receives a phase ("start" or "stop") and an info dictionary with the keys generation, collected, and uncollectable.
import gc
import time
_started = 0.0
def on_gc(phase, info):
global _started
if phase == "start":
_started = time.perf_counter()
else:
elapsed_ms = (time.perf_counter() - _started) * 1000
print(
f"gen {info['generation']}: "
f"collected={info['collected']} "
f"uncollectable={info['uncollectable']} "
f"{elapsed_ms:.3f} ms"
)
gc.callbacks.append(on_gc)
keep = [[] for _ in range(5000)] # many container allocations trigger collections
gc.callbacks.remove(on_gc)In a real service, send these numbers to your metrics system instead of printing them. Look at two things. The first is how often generation 2 runs. The second is how long each run takes. A full collection must visit every tracked object, so its pause grows with the size of the heap.
For a quick look without writing code, gc.set_debug(gc.DEBUG_STATS) makes the collector print a summary to standard error on every run. Turn it off with gc.set_debug(0).
Changing the thresholds
gc.set_threshold(t0, t1, t2) changes the trigger values. Raising t0 makes generation 0 collections less frequent but larger. Setting t0 to 0 turns automatic collection off.
import gc
old = gc.get_threshold()
gc.set_threshold(50_000, old[1], old[2])
print(gc.get_threshold())
gc.set_threshold(*old) # restoreTreat a higher threshold as a trade. You get fewer pauses, and you accept that cyclic garbage stays in memory longer. Objects freed by reference counting are not affected, because that mechanism never waits for the collector.
Pausing the collector for a batch job
Some programs build a large structure of containers in one burst. Every few hundred allocations triggers a collection that walks the growing structure and finds nothing to free. In that case you can pause the collector for the duration of the build.
import gc
from contextlib import contextmanager
@contextmanager
def gc_paused():
was_enabled = gc.isenabled()
gc.disable()
try:
yield
finally:
if was_enabled:
gc.enable()
with gc_paused():
records = [{"id": i, "tags": [i]} for i in range(200_000)]
print(len(records), gc.isenabled()) # 200000 TrueThe context manager restores the previous state, not simply enable(). That matters when the code is called by a caller that had already disabled the collector on purpose.
Freezing objects before forking
Servers that start worker processes with fork have a specific problem. The collector writes to every object it visits, because it updates internal bookkeeping in the object header. Those writes force the operating system to copy memory pages that the parent and child would otherwise share, so a worker's memory grows even if it never changes your data.
gc.freeze() moves all currently tracked objects into a permanent generation that the collector ignores. Call it in the parent after loading your application and before forking.
import gc
# ... import modules and load shared data here ...
gc.collect() # free what is already garbage first
gc.freeze()
print(gc.get_freeze_count() > 0) # True
# ... fork workers here ...Run gc.collect() before freezing. Otherwise you freeze garbage permanently. gc.unfreeze() returns the frozen objects to the oldest generation.
Looking for what is alive
When memory stays high, these tools show what the collector knows about.
| Function | What it gives you |
|---|---|
| `gc.get_objects()` | A list of every tracked container object. On a large heap this list is large, so call it rarely. |
| `gc.get_referrers(obj)` | The tracked objects that refer directly to `obj`. |
| `gc.get_referents(obj)` | The objects that `obj` refers to directly. |
| `gc.garbage` | Objects the collector found but could not free, or all found objects when `DEBUG_SAVEALL` is set. |
A useful pattern is to count live objects by type before and after a suspect operation.
import gc
from collections import Counter
def type_counts():
gc.collect()
return Counter(type(o).__name__ for o in gc.get_objects())
before = type_counts()
cache = [object.__new__(type("Leaky", (), {})) for _ in range(100)]
after = type_counts()
print((after - before)["Leaky"]) # 100Subtracting two Counter objects keeps only the positive differences, so the output lists the types that grew. Call gc.collect() first so that garbage already waiting for collection does not distort the counts.
To inspect the cyclic garbage itself, set gc.set_debug(gc.DEBUG_SAVEALL). The collector then appends unreachable objects to gc.garbage instead of freeing them. Examine them, then clear the list and reset the flag with gc.set_debug(0).
Decision criteria
Change the collector only when you can show it is the problem.
- Measure first. Use callbacks or
DEBUG_STATSto see how often each generation runs and how long the pauses are. - If the pauses come from full collections on a very large heap, consider
gc.freeze()for long-lived data, or raising the thresholds. - If the program builds a big structure and then does other work, pause the collector only for the build.
- If memory grows, do not tune the collector first. Look for a leak with
tracemallocandgc.get_objects(), because a leak means references are still held, and no threshold will free an object that is still reachable. - After any change, measure again. Memory use and pause time both matter, and improving one can worsen the other.
Exercise
A batch job builds a list of 2 million small dictionaries and then processes it. Profiling with gc.callbacks shows many slow generation 2 collections during the build, and almost nothing is collected. What is a safe change, and what must you do to keep it safe?
Show answer
Pause the collector only while building the list, using gc.disable() inside a try/finally (or a context manager like gc_paused) that restores the previous state with gc.enable() only if it was enabled before. The collections during the build find no garbage, so skipping them saves time. Keeping the pause scoped to the build means reference cycles created later are still collected. You could also call gc.collect() once after the build if you want cyclic garbage cleaned at a known point.
Exercise
Why should you call gc.collect() before gc.freeze() in a server that forks workers?
Show answer
gc.freeze() moves every currently tracked object into a permanent generation that the collector never examines. If unreachable cyclic garbage is still waiting to be collected, freezing it means it is never freed. Collecting first removes that garbage, so only live objects are frozen.