Verified Jobs Live
Python Programming Advanced Level ~4 min read

How does Memory Management and Garbage Collection work internally in Python (CPython)?

Quick Revision Summary

Python relies primarily on immediate Reference Counting for memory deallocation and uses a three-generation cyclic garbage collector to detect and reclaim circular references.

Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
Model Answer & Deep-Dive Explanation

CPython memory management consists of a multi-tiered hierarchy:

  1. PyMalloc: A specialized small-object memory allocator that manages blocks, pools, and arenas for objects ≤ 512 bytes, minimizing expensive OS malloc calls.
  2. Reference Counting: Primary GC mechanism. Every Python object has an ob_refcnt field. When a reference is created, count increments; when reference goes out of scope or is deleted (del), count decrements. When count hits 0, memory is immediately deallocated.
  3. Cyclic Garbage Collector: Reference counting cannot collect circular references (e.g. object A references B, and B references A). CPython includes a cyclic GC that divides objects into three generations (Gen 0, Gen 1, Gen 2). Younger generations are collected more frequently based on allocation/deallocation thresholds.

Interviewer Evaluation Points & Scoring Rubric

  • 1 1. Identifies Reference Counting as primary deallocation mechanism. 2. Explains circular reference problem. 3. Mentions generational GC (Gen 0, 1, 2) and PyMalloc.