Memory Management
Python uses reference counting with a cyclic garbage collector. Use weakref to avoid reference cycles and tracemalloc to profile allocations.
Python uses reference counting with a cyclic garbage collector. Use weakref to avoid reference cycles and tracemalloc to profile allocations.
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)
tracemalloc pinpoints exactly which line allocates the most memory — invaluable for leak hunting.