Draws Python object reference graphs with graphviz
npx @tessl/cli install tessl/pypi-objgraph@3.6.00
# objgraph
1
2
A Python module for visualizing Python object reference graphs with graphviz. objgraph helps developers track memory usage, identify memory leaks, and understand object relationships by providing tools to count objects, analyze growth patterns, and generate visual graphs of object references.
3
4
## Package Information
5
6
- **Package Name**: objgraph
7
- **Language**: Python
8
- **Installation**: `pip install objgraph`
9
- **Version**: 3.6.2
10
11
## Core Imports
12
13
```python
14
import objgraph
15
```
16
17
## Basic Usage
18
19
```python
20
import objgraph
21
22
# Count objects by type
23
print(objgraph.count('list')) # Count all list objects
24
print(objgraph.count('dict')) # Count all dict objects
25
26
# Show most common object types
27
objgraph.show_most_common_types()
28
29
# Track object growth between code sections
30
objgraph.show_growth()
31
# ... run some code that might create objects ...
32
objgraph.show_growth() # Shows increases since last call
33
34
# Find objects by type
35
my_lists = objgraph.by_type('list')
36
print(f"Found {len(my_lists)} list objects")
37
38
# Visualize what refers to an object
39
my_object = [1, 2, 3]
40
objgraph.show_backrefs([my_object], filename='backrefs.png')
41
42
# Visualize what an object refers to
43
objgraph.show_refs([my_object], filename='refs.png')
44
```
45
46
## Architecture
47
48
objgraph operates on Python's garbage collector and provides three main interaction patterns:
49
50
- **Statistical Analysis**: Count and categorize objects tracked by the garbage collector
51
- **Growth Monitoring**: Track changes in object counts over time to identify memory leaks
52
- **Reference Visualization**: Generate graphviz diagrams showing object reference relationships
53
54
The module integrates with Python's `gc` module to access tracked objects and uses graphviz for visualization. Optional xdot integration provides interactive graph viewing.
55
56
## Capabilities
57
58
### Object Statistics and Counting
59
60
Functions for counting objects, analyzing type distributions, and getting statistical overviews of memory usage patterns.
61
62
```python { .api }
63
def count(typename, objects=None): ...
64
def typestats(objects=None, shortnames=True, filter=None): ...
65
def most_common_types(limit=10, objects=None, shortnames=True, filter=None): ...
66
def show_most_common_types(limit=10, objects=None, shortnames=True, file=None, filter=None): ...
67
```
68
69
[Object Statistics](./object-statistics.md)
70
71
### Growth Analysis and Monitoring
72
73
Tools for tracking object creation and growth patterns over time, essential for identifying memory leaks and monitoring memory usage.
74
75
```python { .api }
76
def growth(limit=10, peak_stats={}, shortnames=True, filter=None): ...
77
def show_growth(limit=10, peak_stats=None, shortnames=True, file=None, filter=None): ...
78
def get_new_ids(skip_update=False, limit=10, sortby='deltas', shortnames=None, file=None, _state={}): ...
79
```
80
81
[Growth Analysis](./growth-analysis.md)
82
83
### Object Discovery and Access
84
85
Functions for finding specific objects by type or memory address, and identifying potential memory leaks.
86
87
```python { .api }
88
def by_type(typename, objects=None): ...
89
def at(addr): ...
90
def at_addrs(address_set): ...
91
def get_leaking_objects(objects=None): ...
92
```
93
94
[Object Discovery](./object-discovery.md)
95
96
### Reference Chain Analysis
97
98
Tools for tracing reference chains between objects to understand how objects are connected and what keeps them alive.
99
100
```python { .api }
101
def find_ref_chain(obj, predicate, max_depth=20, extra_ignore=()): ...
102
def find_backref_chain(obj, predicate, max_depth=20, extra_ignore=()): ...
103
```
104
105
[Reference Chains](./reference-chains.md)
106
107
### Graph Visualization
108
109
Generate visual representations of object reference graphs using graphviz, with support for interactive viewing and various output formats.
110
111
```python { .api }
112
def show_backrefs(objs, max_depth=3, extra_ignore=(), filter=None, too_many=10, highlight=None, filename=None, extra_info=None, refcounts=False, shortnames=True, output=None, extra_node_attrs=None): ...
113
def show_refs(objs, max_depth=3, extra_ignore=(), filter=None, too_many=10, highlight=None, filename=None, extra_info=None, refcounts=False, shortnames=True, output=None, extra_node_attrs=None): ...
114
def show_chain(*chains, **kw): ...
115
```
116
117
[Graph Visualization](./graph-visualization.md)
118
119
## Utility Functions
120
121
### Module Detection
122
123
```python { .api }
124
def is_proper_module(obj):
125
"""
126
Check if object is a proper module (in sys.modules).
127
128
Args:
129
obj: Object to check
130
131
Returns:
132
bool: True if obj is a proper module
133
"""
134
```
135
136
## Constants
137
138
```python { .api }
139
# Module metadata
140
__version__: str # "3.6.2"
141
__author__: str # "Marius Gedminas (marius@gedmin.as)"
142
__copyright__: str # "Copyright (c) 2008-2023 Marius Gedminas and contributors"
143
__license__: str # "MIT"
144
__date__: str # "2024-10-10"
145
146
# Runtime configuration
147
IS_INTERACTIVE: bool # True if running in IPython/Jupyter
148
```
149
150
## Error Handling
151
152
objgraph functions generally raise standard Python exceptions:
153
- `ValueError`: For invalid parameter combinations (e.g., specifying both `filename` and `output` in visualization functions)
154
- `AttributeError`: For missing object attributes during introspection
155
- `OSError`/`FileNotFoundError`: When output files cannot be created
156
- `ImportError`: When optional dependencies like `graphviz` are missing
157
- Functions with safe representation fallbacks catch generic `Exception` and return safe string alternatives