Garbage collection
Garbage collection reclaims objects that the program can no longer reach. CPython combines reference counting for the common case with a cyclic collector for objects that point at each other.
Detailed Explanation
"GC" in Python talk often means two things. Immediate free-when-count-hits-zero is reference counting. The gc module is the cyclic collector that runs now and then to find groups of objects whose counts are not zero but who are only reachable from each other.
The cyclic collector is generational. New objects live in generation 0. Surviving a collection is promoted. Older generations are scanned less often. gc.get_threshold() and gc.set_threshold tune how many allocations trigger a scan. gc.collect() forces one.
You rarely call gc.collect() in application code. Tests that assert on ResourceWarning or that check for leaks sometimes do. Long-running processes that create many cycles (graphs, ORMs, GUI widgets) can benefit from an explicit collect during idle time, measured first.
gc.disable() turns off the cyclic collector. Reference counting still runs. Disable only if a profiler says collections are a problem and you have no cycles — a rare combination. gc.freeze() (3.7+) moves current objects to a permanent generation, used by some copy-on-write prefork servers so children do not rescan the parent's objects.
gc.get_objects() lists tracked objects and is expensive. gc.get_referrers is a debugging tool, not an API to build features on. gc.set_debug(gc.DEBUG_LEAK) helps find uncollectable objects, usually those with __del__ in a cycle.
Memory that lives in C extensions, memory maps, and file caches is outside this collector. Closing those resources is still your job.
Code Examples
import gc
print(gc.isenabled()) # True
print(gc.get_threshold()) # (700, 10, 10) or similar
n = gc.collect()
print(n) # number of unreachable objects found# A cycle: each dict points at the other. Refcount never hits 0.
a: dict = {}
b: dict = {}
a["other"] = b
b["other"] = a
del a, b
print(gc.collect() >= 0) # collector can reclaim the cycleCommon Gotchas
`gc.disable()` and then creating cycles
the objects stay until you collect or exit. Do not disable in a web process without a measurement.
`__del__` plus cycles
the pair can be uncollectable. Avoid `__del__`.
`get_objects()` in production
it stops the world and can be huge. Use it in a debug build.
Refcounting still frees most objects
the cyclic collector is the backup, not the everyday path.