What is Python's memory management and garbage collection?
Answer
CPython uses reference counting as the primary memory management strategy — every object has a reference count incremented when referenced and decremented when dereferenced. When the count reaches zero, memory is freed immediately. This handles most cases efficiently with no GC pause. However, reference counting fails for circular references (A → B → A). CPython's supplementary cycle garbage collector (the gc module) periodically identifies and frees circular reference cycles. GC is organized into three generations: gen0 (young objects, collected frequently), gen1, gen2 (old objects, collected rarely). Disable GC for performance-critical code (if no circular references): gc.disable(). Profile memory with tracemalloc. Tools: objgraph (visualize object references), memory_profiler (line-by-line memory usage). Python 3.12 improved GC with the new low-impact incremental collector.
Previous
What is Python's @dataclass vs namedtuple vs attrs?
Next
What is Python's __dunder__ (magic) methods?