Python & FastAPI•Part 2: Python Core Language, Internals & Runtime (6 - 25)
Memory management in Python: Reference Counting & Generational GC:
In Simple Words: CPython manages memory in two ways:
- Reference Counting (Immediate): Every object tracks how many variables point to it (
ob_refcnt). When it reaches 0, memory is freed immediately. - Generational Cyclic GC (Background): Detects circular references (
a.b = b; b.a = a) where reference counts never hit 0, grouping objects into 3 generations (Gen 0, 1, 2) based on survival age.
python
import sys, gc
a = []
print(sys.getrefcount(a)) # 2 (variable 'a' + argument passed to getrefcount)
# Creating a reference cycle:
class Node:
pass
n1, n2 = Node(), Node()
n1.other = n2
n2.other = n1
del n1, n2 # Reference count never hits 0; collected by generational GC:
gc.collect() # Manually triggers cyclic garbage collection