On this page
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`)
- > Cyclic Garbage Collection (`gc`) & Weak References (`weakref`)
- > Reducing Instance Overhead with `__slots__`
- > Memory Tracing (`tracemalloc`) & Bytecode (`dis`)
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)
[[stdlib_module/tracemalloc|tracemalloc]]snapshots Python memory allocations by file and line number.[[stdlib_module/dis|dis]]disassembles Python functions into CPython bytecode instructions.
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
- tuts/programming/memory_and_execution
- tuts/programming/memory_and_execution/compilation_interpretation_and_jit
- tuts/programming/memory_and_execution/memory_management_models
- tuts/python3/tutorials
- tuts/python3/tutorials/advanced_python_internals
- tuts/python3/tutorials/advanced_python_internals/concurrency_and_parallelism
- tuts/python3/tutorials/advanced_python_internals/memory_management_and_internals
- tuts/python3/tutorials/advanced_python_internals/python_object_mro_and_initialization
Related notes
- tuts/python3/tutorials/advanced_python_internals Linked here; links to this page; shared tags: #internals, #tutorials
- tuts/python3/tutorials/advanced_python_internals/concurrency_and_parallelism Linked here; links to this page; shared tags: #internals, #tutorials
- tuts/python3/tutorials/advanced_python_internals/python_object_mro_and_initialization Linked here; links to this page; shared tags: #internals, #tutorials
- tuts/programming/memory_and_execution links to this page; shared tags: #internals, #memory
- tuts/programming/memory_and_execution/memory_management_models links to this page; shared tags: #gc, #memory
- tuts/programming/memory_and_execution/compilation_interpretation_and_jit links to this page; shared tags: #memory
- tuts/python3/tutorials links to this page; shared tags: #tutorials
- tuts/python3/stdlib_module/dis Linked here
- tuts/python3/stdlib_module/gc Linked here
- tuts/python3/stdlib_module/sys Linked here