objgraph
objgraph is a Python module that lets you visually explore Python object graphs. It helps in debugging, understanding memory usage, and finding memory leaks by drawing object reference graphs using Graphviz. The library is actively maintained with regular updates for Python version compatibility.
Warnings
- breaking objgraph version 3.6.0 and later dropped support for Python 2.x and Python 3.7. Previous versions (e.g., 3.5.0) dropped Python 3.5 support, and 3.4.1 dropped 3.3 and 3.4.
- gotcha Drawing object graphs with `show_refs()` or `show_backrefs()` requires the external Graphviz system utility to be installed and available in your system's PATH. Without it, image generation will fail.
- gotcha In IPython/Jupyter notebooks, before version 3.5.0, explicitly passing a `filename` argument to `show_refs()` or `show_backrefs()` might still trigger inline graph display instead of only saving to the specified file.
- gotcha For interactive viewing of graphs without saving to a file, `objgraph` can integrate with `xdot`. You'll need to install `xdot` separately (`pip install xdot` or system-wide) and omit the `filename` argument from `show_refs`/`show_backrefs`.
Install
-
pip install objgraph -
pip install objgraph[ipython]
Imports
- objgraph
import objgraph
Quickstart
import objgraph
def create_objects():
x = []
y = [x, [x], {'x_key': x}]
z = {'list_ref': y, 'dict_ref': {'inner_x': x}}
return x, y, z
x, y, z = create_objects()
# Show references reachable from 'y', save to a PNG
objgraph.show_refs([y], filename='sample-graph.png', max_depth=2)
print("Generated sample-graph.png showing references from 'y'")
# Show backreferences to 'x', save to a PNG
objgraph.show_backrefs([x], filename='sample-backref-graph.png', max_depth=2)
print("Generated sample-backref-graph.png showing backreferences to 'x'")
# Show most common types in memory
print("\nMost common types in memory:")
objgraph.show_most_common_types(limit=5)