0
# Object Statistics and Counting
1
2
Functions for analyzing object counts and type distributions in Python programs. These tools help understand memory usage patterns and identify the most common object types tracked by the garbage collector.
3
4
## Capabilities
5
6
### Basic Object Counting
7
8
Count objects of a specific type tracked by the garbage collector.
9
10
```python { .api }
11
def count(typename, objects=None):
12
"""
13
Count objects tracked by the garbage collector with a given class name.
14
15
Args:
16
typename (str): Class name, can be short ('dict') or fully qualified ('mymodule.MyClass')
17
objects (list, optional): Custom collection of objects to search instead of gc.get_objects()
18
19
Returns:
20
int: Number of objects matching the type name
21
22
Note:
23
The garbage collector does not track simple objects like int or str.
24
"""
25
```
26
27
Usage examples:
28
29
```python
30
import objgraph
31
32
# Count built-in types
33
dict_count = objgraph.count('dict')
34
list_count = objgraph.count('list')
35
36
# Count custom classes (short name)
37
my_class_count = objgraph.count('MyClass')
38
39
# Count with fully qualified name
40
specific_count = objgraph.count('mymodule.MyClass')
41
42
# Count within a specific object collection
43
leaking_objects = objgraph.get_leaking_objects()
44
leaking_dicts = objgraph.count('dict', leaking_objects)
45
```
46
47
### Type Statistics Generation
48
49
Generate comprehensive statistics about object type distributions.
50
51
```python { .api }
52
def typestats(objects=None, shortnames=True, filter=None):
53
"""
54
Count the number of instances for each type tracked by the GC.
55
56
Args:
57
objects (list, optional): Custom object collection to analyze
58
shortnames (bool): If True, use short class names; if False, use fully qualified names
59
filter (callable, optional): Function taking one argument returning bool; objects for which filter(obj) returns False are ignored
60
61
Returns:
62
dict: Mapping from type names to instance counts
63
64
Note:
65
Classes with the same name but defined in different modules will be lumped together if shortnames=True.
66
"""
67
```
68
69
Usage examples:
70
71
```python
72
import objgraph
73
74
# Get all type statistics
75
stats = objgraph.typestats()
76
print(f"Lists: {stats.get('list', 0)}")
77
print(f"Dicts: {stats.get('dict', 0)}")
78
79
# Use fully qualified names to distinguish between modules
80
full_stats = objgraph.typestats(shortnames=False)
81
82
# Filter specific objects
83
def is_large_container(obj):
84
return hasattr(obj, '__len__') and len(obj) > 100
85
86
large_container_stats = objgraph.typestats(filter=is_large_container)
87
88
# Analyze specific object collection
89
leaking_objects = objgraph.get_leaking_objects()
90
leak_stats = objgraph.typestats(leaking_objects)
91
```
92
93
### Most Common Types Analysis
94
95
Identify and rank the most frequently occurring object types.
96
97
```python { .api }
98
def most_common_types(limit=10, objects=None, shortnames=True, filter=None):
99
"""
100
Count the names of types with the most instances.
101
102
Args:
103
limit (int): Maximum number of types to return; None for no limit
104
objects (list, optional): Custom object collection to analyze
105
shortnames (bool): If True, use short class names; if False, use fully qualified names
106
filter (callable, optional): Function taking object and returning bool; objects returning False are ignored
107
108
Returns:
109
list: List of (type_name, count) tuples, sorted most-frequent-first
110
"""
111
```
112
113
Usage examples:
114
115
```python
116
import objgraph
117
118
# Get top 10 most common types
119
top_types = objgraph.most_common_types()
120
for type_name, count in top_types:
121
print(f"{type_name}: {count}")
122
123
# Get all types (no limit)
124
all_types = objgraph.most_common_types(limit=None)
125
126
# Get top 5 with fully qualified names
127
top_5_qualified = objgraph.most_common_types(limit=5, shortnames=False)
128
129
# Filter to only container types
130
def is_container(obj):
131
return hasattr(obj, '__len__')
132
133
top_containers = objgraph.most_common_types(
134
limit=5,
135
filter=is_container
136
)
137
```
138
139
### Type Statistics Display
140
141
Print formatted tables of type statistics for easy reading.
142
143
```python { .api }
144
def show_most_common_types(limit=10, objects=None, shortnames=True, file=None, filter=None):
145
"""
146
Print the table of types of most common instances.
147
148
Args:
149
limit (int): Maximum number of types to show
150
objects (list, optional): Custom object collection to analyze
151
shortnames (bool): If True, use short class names; if False, use fully qualified names
152
file (file-like, optional): Output destination; defaults to sys.stdout
153
filter (callable, optional): Function taking object and returning bool; objects returning False are ignored
154
155
Returns:
156
None: Prints formatted output
157
"""
158
```
159
160
Usage examples:
161
162
```python
163
import objgraph
164
import sys
165
166
# Print top 10 to stdout
167
objgraph.show_most_common_types()
168
169
# Print top 5 to stderr
170
objgraph.show_most_common_types(limit=5, file=sys.stderr)
171
172
# Print with fully qualified names
173
objgraph.show_most_common_types(shortnames=False)
174
175
# Print filtered results
176
def is_custom_class(obj):
177
return not type(obj).__module__ in ('builtins', '__builtin__')
178
179
objgraph.show_most_common_types(filter=is_custom_class)
180
181
# Save to file
182
with open('object_stats.txt', 'w') as f:
183
objgraph.show_most_common_types(file=f)
184
```
185
186
Example output:
187
```
188
tuple 8959
189
function 2442
190
wrapper_descriptor 1048
191
dict 953
192
builtin_function_or_method 800
193
```