Python › Memory Management & Garbage Collection

How does the tracemalloc module help track where memory is being allocated in a running program?

Intermediate

Answer

tracemalloc records the Python call stack at the time of each memory allocation, letting you take snapshots and compare them to find exactly which lines of code are responsible for the largest or newest memory allocations -- invaluable for diagnosing memory leaks or unexpectedly high memory usage in long-running applications.
import tracemalloc

tracemalloc.start()
# ... run some code ...
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
for stat in top_stats[:3]:
    print(stat)
Real-world example A web server experiencing gradual memory growth uses tracemalloc to take snapshots an hour apart and diff them, pinpointing a specific caching function that never evicts old entries.

Common follow-ups: How do you compare two snapshots to find leaks with compare_to?;What's the performance overhead of running tracemalloc in production?