Back
+20 XP
Concept

Cyclic Garbage Collector: Generations & PyGC_Head

Reference counts cannot reclaim cyclic graphs (`a.ref = b; b.ref = a`). CPython's generational GC prepends container objects with a `PyGC_Head` linked-list header, scanning 3 age generations (0, 1, 2) to detect and reclaim isolated cyclic subgraphs through trial decrements ♻️🔍.

python
import gc

class CircularNode:
    def __init__(self, name):
        self.name = name
        self.peer = None

# Create an isolated reference cycle:
node_1 = CircularNode("A")
node_2 = CircularNode("B")
node_1.peer = node_2
node_2.peer = node_1

# Delete external handles (refcounts remain 1!):
del node_1, node_2

# Explicit generational collection cleans the cycle:
collected = gc.collect()
print(f"Cyclic objects reclaimed from memory: {collected} 🚀")

# 80. Cyclic Garbage Collector: Generations & PyGC_Head Beginners assume Python's garbage collector works like Java's or Go's mark-and-sweep GC. In reality, CPython reclaims 99% of objects instantaneously via reference counting. The cyclic GC exists only to resolve the fatal flaw of reference counts: cycles 🛑. ```python # The Reference Cycle Trap: # A -> references B (B refcount = 1) # B -> references A (A refcount = 1) # del A, del B -> Neither refcount drops to 0! Leaked in RAM forever without GC! ``` ### The Generational GC Mechanics 1. **`PyGC_Head` Linked List**: Only container objects (lists, dicts, custom class instances) that can hold references are tracked. Atomic types (integers, strings) are never tracked by the cyclic GC. 2. **The 3 Generations (Weak Generational Hypothesis)**: - **Generation 0**: Newly allocated containers. Scanned frequently. - **Generation 1**: Survives Gen 0 collection. Scanned less often. - **Generation 2**: Long-lived objects (module globals, caches). Scanned rarely. 3. **Trial Decrement Algorithm**: To find cycles without deallocating live objects, GC copies all `ob_refcnt` values, decrements them by the references originating from within the container pool. Any object whose trial refcount reaches 0 is part of an isolated cycle and is safely wiped ♻️🔍. --- ### Interactive Pop-Quiz 🧠 #### Why can pure reference counting never deallocate an isolated two-node circular reference (a.ref = b; b.ref = a) when both variables are deleted? - [ ] Because each node's internal reference to the other keeps their `ob_refcnt` at 1 even after all external references are dropped ♻️ - [ ] Because circular objects are automatically saved to virtual swap memory - [ ] Because the operating system kernel marks circular pointers as read-only - [ ] Because Python raises an UnhandledCycleException before deallocating --- ### Practical Challenge 🎯 Disable automatic garbage collection with `gc.disable()`. Create two instances of a class `Cycle` referencing each other. Delete the local references with `del`. Verify `gc.collect()` reclaims the cycle (returning `>= 2`), re-enable GC with `gc.enable()`, and print `'GC_CYCLE_RECLAIMED'`. <details> <summary>Solution</summary> ```python import gc gc.disable() class Cycle: def __init__(self): self.link = None c1 = Cycle() c2 = Cycle() c1.link = c2 c2.link = c1 del c1, c2 reclaimed = gc.collect() gc.enable() assert reclaimed >= 2 print("GC_CYCLE_RECLAIMED") ``` </details>

Checkpoint

Why can pure reference counting never deallocate an isolated two-node circular reference (`a.ref = b; b.ref = a`) when both variables are deleted? 🧠

Practice

Disable automatic garbage collection with `gc.disable()`. Create two instances of a class `Cycle` referencing each other. Delete the local references with `del`. Verify `gc.collect()` reclaims the cycle (returning `>= 2`), re-enable GC with `gc.enable()`, and print `'GC_CYCLE_RECLAIMED'`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks