Python Reference ยท Standard Library: Concurrency, Network and Tools
The gc module
Reference for Python's gc module: gc.collect(), enable and disable, reference cycles, weak references, thresholds, get_referrers and when to touch the collector.
Python frees most objects the moment nothing refers to them any more, using reference counting. That does not work for reference cycles, where objects point at each other and keep every count above zero. The gc module is the interface to the cyclic garbage collector that finds and frees those groups.
You rarely need it. It is useful for tests that check for leaks, for tuning programs that create huge numbers of container objects, and for understanding why an object is still alive.
import gc print(gc.collect()) # number of unreachable objects found
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
import gc gc.collect(generation=2) gc.enable() gc.disable() gc.isenabled() gc.get_threshold() gc.set_threshold(threshold0, threshold1=None, threshold2=None) gc.get_count() gc.get_referrers(*objs) gc.get_referents(*objs) gc.is_tracked(obj) gc.freeze()
| Function | Description |
|---|---|
collect(generation=2) |
Runs a collection now and returns the number of unreachable objects it found. The default collects everything. |
enable() / disable() / isenabled() |
Turn automatic collection on or off, or ask whether it is on. Reference counting is not affected. |
get_threshold() / set_threshold(...) |
Read or change the numbers that decide when automatic collection runs. |
get_count() |
Returns a tuple of the current allocation counts per generation. |
get_stats() |
Returns a list of dicts with collections, collected and uncollectable per generation. |
get_referrers(*objs) |
Lists the container objects that refer to any of the arguments. |
get_referents(*objs) |
Lists the objects that the arguments refer to directly. |
is_tracked(obj) |
Tells whether the collector watches this object (containers usually yes, plain numbers and strings no). |
freeze() / unfreeze() |
Move all current objects out of future collections, or back. Useful before forking worker processes. |
callbacks |
A list of functions called before and after each collection with (phase, info). |
Return value: collect() returns an int; isenabled() and is_tracked() return bool; get_threshold() and get_count() return tuples; the get_* functions that list objects return lists.
Raises: ValueError if the generation passed to collect() is invalid, and TypeError for wrong argument types.
Usage notes
- Reference counting does the common work. An object with no cycles is freed immediately when its last reference disappears.
gconly handles what counting cannot. gc.disable()does not stop memory from being freed. It only stops the automatic cycle search. Programs that create no cycles, or that build a large structure once, sometimes disable it and callgc.collect()at a chosen moment.- Do not rely on
__del__timing. Finalizers on objects in a cycle run when the collector gets to them, not atdel. Since Python 3.4 such objects are collectable. Prefer context managers for cleanup. - Weak references break cycles. A parent that points to children while children hold a
weakref(or a plain id) back to the parent never forms a strong cycle. Seeweakref. - Debugging leaks: call
gc.collect(), then useget_referrers()to see who still holds an object. Remember that the list returned also contains the frame running your debugging code. get_objects()andget_referrers()are slow on big programs. Use them for investigation, never in hot paths.- The exact thresholds and generations are implementation details. They have been tuned across versions (the collector in 3.12 and 3.13 differs from the one in 3.14), so write code that reads them, never code that depends on specific values.
gc.freeze()(3.7+) moves everything allocated so far into a permanent generation. It is aimed at servers that preload data and then fork.- Pyodide and other runtimes: all of this describes CPython. Other implementations, such as PyPy, collect differently and have no reference counts.
Related
weakref,copy,id()sysforsys.getrefcount()andsys.getsizeof()- Lessons: Memory management, Performance