Python › Memory Management & Garbage Collection

How does Python's generational garbage collector work, and why generations?

Intermediate

Answer

CPython's gc module divides tracked objects into three generations (0, 1, 2) based on survival: new objects start in generation 0; objects that survive a collection are promoted to the next generation. Younger generations are collected more frequently since most objects die young (the generational hypothesis), while older, longer-lived objects are scanned less often, improving overall efficiency.
import gc

print(gc.get_threshold())  # e.g., (700, 10, 10) -- collection thresholds per generation
gc.collect()  # force a full collection
print(gc.get_count())  # current allocation counts per generation
Real-world example A long-running server process periodically calls gc.collect() during idle periods to proactively reclaim cyclic garbage before it accumulates and causes memory pressure spikes.

Common follow-ups: What triggers an automatic collection cycle?;How do you tune the thresholds for a specific workload?