Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Memory & performanceSeniorOccasionalPerformance

How does the built-in `tracemalloc` module help track down a memory leak or unexpectedly high memory usage?

Answer

`tracemalloc` records the Python call stack behind every memory allocation that Python itself makes through its own tracked memory domains, once started with `tracemalloc.start()`, letting you take memory usage "snapshots" at different points in a program's life and compute a `snapshot2.compare_to(snapshot1, "lineno")` diff that ranks which specific lines of code are responsible for the largest growth in allocated memory between the two points, with a configurable traceback depth. This is far more targeted than watching overall process memory in a system monitor for tracking Python-level allocation growth, because it attributes growth directly to Python source lines. It does not see everything the process uses, though: allocations made by native C extensions or libraries outside Python's own tracked allocation domains, and other contributors to overall process (RSS) memory, fall outside what `tracemalloc` reports, so it complements rather than replaces a system-level memory profiler when native memory growth is the suspect.

Strong answer includes

  • traces Python-managed allocation blocks after tracing starts, not arbitrary native/process memory
  • snapshots at two points in time, compared with compare_to(); traceback depth is configurable
  • does not explain all RSS/native memory growth from C extensions

Practical example

Comparing a snapshot taken after startup with one taken after processing 10,000 requests can pinpoint a single

Python example
cache[key] = large_object

line that never evicts entries as the source of a slow memory leak.

#profiling#memory-management

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modules