Pympler

1.1 · active · verified Thu Apr 09

Pympler is a development tool designed to measure, monitor, and analyze the memory behavior of Python objects in a running application. It provides detailed insights into the size and lifetime of Python objects, aiding in the identification of memory bloat, leaks, and other undesirable runtime behaviors. The current stable version is 1.1.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic memory profiling using `pympler.asizeof` to get the recursive size of an object, and `pympler.muppy` and `pympler.summary` to get a snapshot and diff of all objects in memory. It also includes a simplified example of `pympler.tracker` to show changes over time.

from pympler import asizeof, muppy, summary

class MyObject:
    def __init__(self, data):
        self.data = data
        self.large_list = [0] * 1000 # A list consuming some memory

# 1. Measure the size of an individual object recursively
obj = MyObject('some string data')
print(f"Size of obj: {asizeof.asizeof(obj)} bytes")

# 2. Get a summary of all objects in memory
all_objects_before = muppy.get_objects()
sum1 = summary.summarize(all_objects_before)
print("\n--- Memory Summary (Before) ---")
summary.print_(sum1, limit=5) # Print top 5 largest object types

# Create more objects
my_list = [MyObject(f'data_{i}') for i in range(10)]

# 3. Get a diff in memory usage
all_objects_after = muppy.get_objects()
sum2 = summary.summarize(all_objects_after)
print("\n--- Memory Summary (After, diff) ---")
diff = summary.diff(sum1, sum2)
summary.print_(diff, limit=5) # Print top 5 changes

# Example of tracker for change over time (simplified)
tr = tracker.SummaryTracker()

# Perform some operations that might create new objects
def create_temp_objects():
    local_list = ["temp_str"] * 500

create_temp_objects()

print("\n--- Tracker Diff after create_temp_objects() ---")
tr.print_diff(limit=5)

view raw JSON →