objsize
The objsize Python package provides functionality for traversing an object's subtree and calculating its total memory consumption in bytes (deep size). It leverages Python's internal Garbage Collection (GC) implementation, designed to ignore commonly shared objects like singletons and type objects for more accurate deep sizing. It's currently in version 0.8.0 and generally has infrequent releases.
Warnings
- gotcha By design, `objsize` attempts to ignore singletons (e.g., `None`) and type objects (classes, modules, functions, lambdas) when calculating deep size. This means they won't contribute to the reported size of the object's subtree, as they are considered shared.
- gotcha Unlike some alternatives (e.g., Pympler), `objsize` uses a Breadth-First Search (BFS) approach internally to traverse object subtrees, avoiding recursive calls. This prevents hitting Python's default recursion depth limits, but users migrating from recursive deep-sizing tools should be aware of this architectural difference.
- gotcha For 'special objects' or objects with non-standard memory management (e.g., `weakref.proxy` or objects managing off-heap memory), `objsize`'s default calculation might not fully capture their size. You may need to provide custom handlers.
Install
-
pip install objsize
Imports
- get_deep_size
from objsize import get_deep_size
Quickstart
import objsize
my_data = {'name': 'Alice', 'age': 30, 'hobbies': ['reading', 'coding']}
deep_size_bytes = objsize.get_deep_size(my_data)
print(f"The deep size of my_data is: {deep_size_bytes} bytes")
another_obj = ['hello', 'world']
total_deep_size = objsize.get_deep_size(my_data, another_obj)
print(f"The deep size of multiple objects is: {total_deep_size} bytes")