On this page
  1. Memory Management and Internals
  2. Contents
  3. Reference Counting (sys.getrefcount)
  4. Cyclic Garbage Collection (gc) & Weak References (weakref)
  5. Reducing Instance Overhead with __slots__
  6. Memory Tracing (tracemalloc) & Bytecode (dis)

Memory Management and Internals

Prev: Concurrency and Parallelism | Up: Advanced Python Internals | Next: Python Object, MRO & Initialization Dunder Flow
Rel: Python Object, MRO & Initialization Dunder Flow, gc, sys, weakref, tracemalloc, dis
Ref: docs.python.org — gc | docs.python.org — tracemalloc
Tags: #public #python3 #tutorials #internals #memory #gc #slots


Contents


Reference Counting (sys.getrefcount)

CPython's primary memory management mechanism is reference counting: every PyObject tracks how many references point to it, and deallocates immediately when the count reaches zero.

import sys

obj = object()
print(sys.getrefcount(obj))  # 2 (1 for `obj`, 1 temporary arg to getrefcount)
alias = obj
print(sys.getrefcount(obj))  # 3
del alias
print(sys.getrefcount(obj))  # 2

Cyclic Garbage Collection (gc) & Weak References (weakref)

Reference counting alone cannot reclaim reference cycles (a.ref = b; b.ref = a). CPython's generational cyclic collector ([[stdlib_module/gc|gc]]) detects and collects unreachable cycles. Use [[stdlib_module/weakref|weakref]] to reference objects (such as caches or parent pointers) without increasing their reference count.

import gc
import weakref

class Node:
    def __init__(self, name: str) -> None:
        self.name = name
        self.other = None

a, b = Node("a"), Node("b")
a.other, b.other = b, a
ref_a = weakref.ref(a)

del a, b
collected = gc.collect()
print("Collected objects:", collected, "weakref alive:", ref_a() is not None)

Reducing Instance Overhead with __slots__

By default, every instance stores its attributes in a per-instance __dict__ hash table. Defining __slots__ replaces __dict__ with fixed C-level descriptor offsets, cutting memory footprint and speeding up attribute access.

import sys

class PointDict:
    def __init__(self, x: float, y: float) -> None:
        self.x = x
        self.y = y

class PointSlots:
    __slots__ = ("x", "y")
    def __init__(self, x: float, y: float) -> None:
        self.x = x
        self.y = y

p_dict = PointDict(1.0, 2.0)
p_slot = PointSlots(1.0, 2.0)
print("With __dict__:", sys.getsizeof(p_dict) + sys.getsizeof(p_dict.__dict__), "bytes")
print("With __slots__:", sys.getsizeof(p_slot), "bytes")

Note: for Method Resolution Order (MRO) and object initialization internals, see Python Object, MRO & Initialization Dunder Flow.


Memory Tracing (tracemalloc) & Bytecode (dis)

import dis
import tracemalloc

tracemalloc.start()
data = [i * i for i in range(10_000)]
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(f"Current: {current / 1024:.1f} KiB, Peak: {peak / 1024:.1f} KiB")

def add(a, b):
    return a + b

dis.dis(add)

Linked from

Related notes