Draws Python object reference graphs with graphviz
—
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.
Count objects of a specific type tracked by the garbage collector.
def count(typename, objects=None):
"""
Count objects tracked by the garbage collector with a given class name.
Args:
typename (str): Class name, can be short ('dict') or fully qualified ('mymodule.MyClass')
objects (list, optional): Custom collection of objects to search instead of gc.get_objects()
Returns:
int: Number of objects matching the type name
Note:
The garbage collector does not track simple objects like int or str.
"""Usage examples:
import objgraph
# Count built-in types
dict_count = objgraph.count('dict')
list_count = objgraph.count('list')
# Count custom classes (short name)
my_class_count = objgraph.count('MyClass')
# Count with fully qualified name
specific_count = objgraph.count('mymodule.MyClass')
# Count within a specific object collection
leaking_objects = objgraph.get_leaking_objects()
leaking_dicts = objgraph.count('dict', leaking_objects)Generate comprehensive statistics about object type distributions.
def typestats(objects=None, shortnames=True, filter=None):
"""
Count the number of instances for each type tracked by the GC.
Args:
objects (list, optional): Custom object collection to analyze
shortnames (bool): If True, use short class names; if False, use fully qualified names
filter (callable, optional): Function taking one argument returning bool; objects for which filter(obj) returns False are ignored
Returns:
dict: Mapping from type names to instance counts
Note:
Classes with the same name but defined in different modules will be lumped together if shortnames=True.
"""Usage examples:
import objgraph
# Get all type statistics
stats = objgraph.typestats()
print(f"Lists: {stats.get('list', 0)}")
print(f"Dicts: {stats.get('dict', 0)}")
# Use fully qualified names to distinguish between modules
full_stats = objgraph.typestats(shortnames=False)
# Filter specific objects
def is_large_container(obj):
return hasattr(obj, '__len__') and len(obj) > 100
large_container_stats = objgraph.typestats(filter=is_large_container)
# Analyze specific object collection
leaking_objects = objgraph.get_leaking_objects()
leak_stats = objgraph.typestats(leaking_objects)Identify and rank the most frequently occurring object types.
def most_common_types(limit=10, objects=None, shortnames=True, filter=None):
"""
Count the names of types with the most instances.
Args:
limit (int): Maximum number of types to return; None for no limit
objects (list, optional): Custom object collection to analyze
shortnames (bool): If True, use short class names; if False, use fully qualified names
filter (callable, optional): Function taking object and returning bool; objects returning False are ignored
Returns:
list: List of (type_name, count) tuples, sorted most-frequent-first
"""Usage examples:
import objgraph
# Get top 10 most common types
top_types = objgraph.most_common_types()
for type_name, count in top_types:
print(f"{type_name}: {count}")
# Get all types (no limit)
all_types = objgraph.most_common_types(limit=None)
# Get top 5 with fully qualified names
top_5_qualified = objgraph.most_common_types(limit=5, shortnames=False)
# Filter to only container types
def is_container(obj):
return hasattr(obj, '__len__')
top_containers = objgraph.most_common_types(
limit=5,
filter=is_container
)Print formatted tables of type statistics for easy reading.
def show_most_common_types(limit=10, objects=None, shortnames=True, file=None, filter=None):
"""
Print the table of types of most common instances.
Args:
limit (int): Maximum number of types to show
objects (list, optional): Custom object collection to analyze
shortnames (bool): If True, use short class names; if False, use fully qualified names
file (file-like, optional): Output destination; defaults to sys.stdout
filter (callable, optional): Function taking object and returning bool; objects returning False are ignored
Returns:
None: Prints formatted output
"""Usage examples:
import objgraph
import sys
# Print top 10 to stdout
objgraph.show_most_common_types()
# Print top 5 to stderr
objgraph.show_most_common_types(limit=5, file=sys.stderr)
# Print with fully qualified names
objgraph.show_most_common_types(shortnames=False)
# Print filtered results
def is_custom_class(obj):
return not type(obj).__module__ in ('builtins', '__builtin__')
objgraph.show_most_common_types(filter=is_custom_class)
# Save to file
with open('object_stats.txt', 'w') as f:
objgraph.show_most_common_types(file=f)Example output:
tuple 8959
function 2442
wrapper_descriptor 1048
dict 953
builtin_function_or_method 800Install with Tessl CLI
npx tessl i tessl/pypi-objgraph