SyntaxStudy
Sign Up
Python Garbage Collection and Memory
Python Advanced 5 min read

Garbage Collection and Memory

Memory Management

Python uses reference counting with a cyclic garbage collector. Use weakref to avoid reference cycles and tracemalloc to profile allocations.

Example
import gc, weakref, tracemalloc

class Node:
    def __init__(self, val): self.val = val; self.next = None

# Avoid cycle with weakref
class Parent:
    def __init__(self): self.child = None
class Child:
    def __init__(self, parent): self.parent = weakref.ref(parent)

# Profile allocations
tracemalloc.start()
create_lots_of_objects()
snapshot = tracemalloc.take_snapshot()
top = snapshot.statistics("lineno")[:5]
for stat in top: print(stat)
Pro Tip

tracemalloc pinpoints exactly which line allocates the most memory — invaluable for leak hunting.