How does Python's generational garbage collector complement reference counting to handle cycles?
Answer
The `gc` module runs a separate cycle-detecting collector on top of reference counting, specifically to find and free groups of objects that reference each other but are unreachable from anywhere else in the program. It organizes objects into three generations based on how long they have survived previous collection passes; new objects start in generation 0, which is collected most frequently, and objects that survive a collection are promoted to older generations that are scanned less often, on the empirically-motivated assumption that most objects die young while a few live a long time.
Strong answer includes
- a separate cycle-detecting collector runs alongside reference counting
- three generations, newest collected most frequently
- based on the assumption that most objects die young
Practical example
A short-lived list built and discarded inside a function is almost always cleaned up by reference counting alone before generation-0 collection even runs; a long-lived cache dictionary eventually gets promoted to generation 2 and is scanned rarely.