### Install Python Call Graph Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/README.md Use pip to install the python-call-graph package. This is the first step before using the library. ```shell pip install python-call-graph ``` -------------------------------- ### Install Python Call Graph Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Install the library using pip. Graphviz is also required for Graphviz output. ```shell pip install python-call-graph ``` ```shell # macOS brew install graphviz # Debian / Ubuntu sudo apt-get install graphviz ``` -------------------------------- ### PyCallGraph Manual Start/Stop/Generate Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt For fine-grained control, you can explicitly call start(), stop(), and generate() methods of the PyCallGraph instance. ```APIDOC ## PyCallGraph Manual start / stop / generate For fine-grained control, call `start()`, `stop()`, and `generate()` explicitly instead of using the context manager. ### Usage ```python from pycallgraph import PyCallGraph from pycallgraph import Config from pycallgraph.output import GraphvizOutput graphviz = GraphvizOutput(output_file='output.png') pycallgraph = PyCallGraph(output=graphviz, config=Config(include_stdlib=True)) pycallgraph.start() import html.parser # trace module import calls pycallgraph.stop() # Customize output before rendering graphviz.output_file = 'html_parser_import.png' pycallgraph.generate() # writes the file ``` ``` -------------------------------- ### Manually Control PyCallGraph Tracing Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Manually start, stop, and generate the call graph for fine-grained control over the tracing process. This example traces module import calls. ```python from pycallgraph import PyCallGraph from pycallgraph import Config from pycallgraph.output import GraphvizOutput graphviz = GraphvizOutput(output_file='output.png') pycallgraph = PyCallGraph(output=graphviz, config=Config(include_stdlib=True)) pycallgraph.start() import html.parser # trace module import calls pycallgraph.stop() # Customize output before rendering graphviz.output_file = 'html_parser_import.png' pycallgraph.generate() # writes the file ``` -------------------------------- ### Run PyCallGraph from Command Line Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/README.md Execute pycallgraph from the command line to generate a call graph visualization for a Python script. Ensure Graphviz is installed as it's used for output. ```shell pycallgraph graphviz -- ./mypythonscript.py ``` -------------------------------- ### PyCallGraph Context Manager Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Use PyCallGraph as a context manager to automatically start tracing on __enter__ and stop/generate output on __exit__. ```APIDOC ## PyCallGraph Context Manager Use `PyCallGraph` as a context manager to automatically start tracing on `__enter__` and stop/generate output on `__exit__`. ### Usage ```python from pycallgraph import PyCallGraph from pycallgraph.output import GraphvizOutput graphviz = GraphvizOutput() graphviz.output_file = 'mygraph.png' with PyCallGraph(output=graphviz): # All calls inside this block are traced result = my_function() # mygraph.png is generated automatically on exit ``` ``` -------------------------------- ### Group Nodes Visually with Grouper Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Configure visual clustering of nodes in the output graph using the Grouper class. Provide a list of glob patterns to group functions by module or custom clusters. This example shows grouping submodules into named clusters. ```python from pycallgraph import PyCallGraph, Config, GlobbingFilter, Grouper from pycallgraph.output import GraphvizOutput # Group submodules together into named clusters trace_grouper = Grouper(groups=[ 'myapp.models.*', # cluster: "myapp.models" 'myapp.views.*', # cluster: "myapp.views" 'myapp.*.report', # cluster: "myapp.*.report" (wildcard kept) ]) config = Config() config.trace_filter = GlobbingFilter() # trace everything config.trace_grouper = trace_grouper with PyCallGraph(output=GraphvizOutput(output_file='grouped.png'), config=config): run_application() # Callable usage g = Grouper(groups=['myapp.models.*']) print(g('myapp.models.User')) # 'myapp.models' print(g('other.module.func')) # 'other' ``` -------------------------------- ### Configure PyCallGraph with Custom Settings Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Pass a Config object to PyCallGraph to override default tracing and output settings. This example shows how to enable verbose output, group functions by module, and set a maximum call depth. ```python from pycallgraph import PyCallGraph, Config, GlobbingFilter from pycallgraph.output import GraphvizOutput config = Config( verbose=True, # print progress messages debug=False, # print raw DOT source groups=True, # visually group functions by module threaded=False, # process traces asynchronously (experimental) memory=False, # track memory usage (experimental) include_stdlib=False, # include Python standard library calls max_depth=5, # limit call stack depth ) # Override the default trace filter config.trace_filter = GlobbingFilter( include=['myapp.*'], exclude=['myapp.utils.debug_*'], ) with PyCallGraph(output=GraphvizOutput(output_file='app.png'), config=config): run_application() ``` -------------------------------- ### Use PyCallGraph API for Profiling Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/README.md Integrate the PyCallGraph module into your Python code to profile specific sections. This example uses GraphvizOutput and requires the code_to_profile() function to be defined. ```python from pycallgraph import PyCallGraph from pycallgraph.output import GraphvizOutput with PyCallGraph(output=GraphvizOutput()): code_to_profile() ``` -------------------------------- ### Run Regex Matching Without Grouping Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/docs/examples/regexp_ungrouped.md This script analyzes words from a dictionary to find those starting and ending with the same letter and containing consecutive identical letters. It uses PyCallGraph to trace the execution flow when grouping is set to False. ```python #!/usr/bin/env python ''' Runs a regular expression over the first few hundred words in a dictionary to find if any words start and end with the same letter, and having two of the same letters in a row. ''' import argparse import re from pycallgraph import PyCallGraph from pycallgraph import Config from pycallgraph.output import GraphvizOutput class RegExp(object): def main(self): parser = argparse.ArgumentParser() parser.add_argument('--grouped', action='store_true') conf = parser.parse_args() if conf.grouped: self.run('regexp_grouped.png', Config(groups=True)) else: self.run('regexp_ungrouped.png', Config(groups=False)) def run(self, output, config): graphviz = GraphvizOutput() graphviz.output_file = output self.expression = r'^([^s]).*(.)\2.*\1$' with PyCallGraph(config=config, output=graphviz): self.precompiled() self.onthefly() def words(self): a = 200 for word in open('/usr/share/dict/words'): yield word.strip() a -= 1 if not a: return def precompiled(self): reo = re.compile(self.expression) for word in self.words(): reo.match(word) def onthefly(self): for word in self.words(): re.match(self.expression, word) if __name__ == '__main__': RegExp().main() ``` -------------------------------- ### Filter Function Calls with GlobbingFilter Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Use GlobbingFilter to include or exclude function calls based on Unix shell-style wildcard patterns. Exclude patterns are evaluated before include patterns. This example demonstrates filtering specific modules and internal helpers. ```python from pycallgraph import PyCallGraph, Config, GlobbingFilter from pycallgraph.output import GraphvizOutput # Include only specific modules, exclude internal helpers trace_filter = GlobbingFilter( include=['myapp.*', 'requests.*'], exclude=['myapp.*.internal_*', 'pycallgraph.*'], ) config = Config() config.trace_filter = trace_filter with PyCallGraph(output=GraphvizOutput(output_file='filtered.png'), config=config): my_function() # Direct callable use — returns True if function should be traced f = GlobbingFilter(include=['foo.*'], exclude=['foo.bar']) print(f('foo.baz')) # True print(f('foo.bar')) # False print(f('other')) # False ``` -------------------------------- ### Generate Call Graph with Options Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/docs/guide/command_line_usage.md This command generates a call graph image named 'setup.png' for 'setup.py', passing command-line arguments to the script. ```bash pycallgraph graphviz --output-file=setup.png -- setup.py --dry-run install ``` -------------------------------- ### Use PickleOutput for Deferred Rendering Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Serialize the trace processor to a pickle file for later rendering. This allows deferred or repeated rendering without re-executing the traced code. ```python from pycallgraph import PyCallGraph from pycallgraph.output import PickleOutput with PyCallGraph(output=PickleOutput(output_file='trace.pkl')): my_function() # Later, load the pickle and render with a different output import pickle with open('trace.pkl', 'rb') as f: processor = pickle.load(f) ``` -------------------------------- ### PickleOutput Configuration Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt PickleOutput serializes the trace processor to a pickle file, allowing for deferred or repeated rendering without re-running the program. ```APIDOC ## PickleOutput Serializes the trace processor to a pickle file for deferred or repeated rendering without re-running the program. ### Configuration Options - `output_file` (str): The name of the output pickle file. Default: 'trace.pkl'. ### Usage ```python from pycallgraph import PyCallGraph from pycallgraph.output import PickleOutput with PyCallGraph(output=PickleOutput(output_file='trace.pkl')): my_function() # Later, load the pickle and render with a different output import pickle with open('trace.pkl', 'rb') as f: processor = pickle.load(f) ``` ``` -------------------------------- ### Trace Django Core Modules Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/docs/guide/command_line_usage.md Run Django's 'manage.py' script with verbose output, including standard library calls, and filtering to trace only 'django.core.*' modules. This helps manage the size of the generated graph for large projects. ```bash pycallgraph -v --stdlib --include "django.core.*" graphviz -- ./manage.py syncdb --noinput ``` -------------------------------- ### Generate Basic Call Graph Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/docs/guide/command_line_usage.md Use this command to create a call graph image named 'pycallgraph.png' from 'myprogram.py'. ```bash pycallgraph graphviz -- ./myprogram.py ``` -------------------------------- ### Configure GraphvizOutput Options Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Customize Graphviz output settings such as the output file, type, layout engine, and font properties. ```python from pycallgraph import PyCallGraph from pycallgraph.output import GraphvizOutput graphviz = GraphvizOutput( output_file='graph.svg', # default: 'pycallgraph.png' output_type='svg', # default: 'png' tool='dot', # graphviz layout engine font_name='Verdana', # default font font_size=7, # node font size group_font_size=10, # cluster label font size ) with PyCallGraph(output=graphviz): my_function() # Produces graph.svg ``` -------------------------------- ### Generate Multiple Output Formats Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Produce multiple call graph output formats (e.g., PNG and GDF) in a single tracing run by passing a list of output instances. ```python from pycallgraph import PyCallGraph from pycallgraph.output import GraphvizOutput, GephiOutput outputs = [ GraphvizOutput(output_file='graph.png'), GephiOutput(output_file='graph.gdf'), ] with PyCallGraph(output=outputs): my_application() ``` -------------------------------- ### GraphvizOutput Configuration Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Configure GraphvizOutput to render call graphs as images (PNG, SVG, PDF, DOT, etc.) using Graphviz layout engines. ```APIDOC ## GraphvizOutput Renders the call graph as an image (PNG, SVG, PDF, PS, DOT, etc.) using the Graphviz `dot` tool (or `neato`, `fdp`, `sfdp`, `twopi`, `circo`). ### Configuration Options - `output_file` (str): The name of the output file. Default: 'pycallgraph.png'. - `output_type` (str): The image format. Default: 'png'. - `tool` (str): The Graphviz layout engine to use. Default: 'dot'. - `font_name` (str): The font name for nodes. Default: 'Verdana'. - `font_size` (int): The font size for nodes. Default: 7. - `group_font_size` (int): The font size for cluster labels. Default: 10. ### Usage ```python from pycallgraph import PyCallGraph from pycallgraph.output import GraphvizOutput graphviz = GraphvizOutput( output_file='graph.svg', output_type='svg', tool='dot', font_name='Verdana', font_size=7, group_font_size=10, ) with PyCallGraph(output=graphviz): my_function() # Produces graph.svg ``` ``` -------------------------------- ### Hierarchical Edge Bundling Visualization (JavaScript) Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/examples/json/radial.html This is the main JavaScript code for creating the hierarchical edge bundling visualization. It sets up the SVG canvas, loads data, and renders nodes and links. Adjust the 'tension' of the lines using the range input. ```javascript var w = 1280, h = 800, rx = w / 2, ry = h / 2, m0, rotate = 0; var splines = []; var cluster = d3.layout.cluster() .size([360, ry - 120]) .sort(function(a, b) { return d3.ascending(a.key, b.key); }); var bundle = d3.layout.bundle(); var line = d3.svg.line.radial() .interpolate("bundle") .tension(.85) .radius(function(d) { return d.y; }) .angle(function(d) { return d.x / 180 * Math.PI; }); // Chrome 15 bug: var div = d3.select("body").insert("div", "h2") .style("top", "-80px") .style("left", "-160px") .style("width", w + "px") .style("height", w + "px") .style("position", "absolute") .style("-webkit-backface-visibility", "hidden"); var svg = div.append("svg:svg") .attr("width", w) .attr("height", w) .append("svg:g") .attr("transform", "translate(" + rx + "," + ry + ")"); svg.append("svg:path") .attr("class", "arc") .attr("d", d3.svg.arc().outerRadius(ry - 120).innerRadius(0).startAngle(0).endAngle(2 * Math.PI)) .on("mousedown", mousedown); d3.json("flare-imports.json", function(classes) { var nodes = cluster.nodes(packages.root(classes)), links = packages.imports(nodes), splines = bundle(links); var path = svg.selectAll("path.link") .data(links) .enter().append("svg:path") .attr("class", function(d) { return "link source-" + d.source.key + " target-" + d.target.key; }) .attr("d", function(d, i) { return line(splines[i]); }); svg.selectAll("g.node") .data(nodes.filter(function(n) { return !n.children; })) .enter().append("svg:g") .attr("class", "node") .attr("id", function(d) { return "node-" + d.key; }) .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; }) .append("svg:text") .attr("dx", function(d) { return d.x < 180 ? 8 : -8; }) .attr("dy", ".31em") .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; }) .attr("transform", function(d) { return d.x < 180 ? null : "rotate(180)"; }) .text(function(d) { return d.key; }) .on("mouseover", mouseover) .on("mouseout", mouseout); d3.select("input[type=range]").on("change", function() { line.tension(this.value / 100); path.attr("d", function(d, i) { return line(splines[i]); }); }); }); d3.select(window) .on("mousemove", mousemove) .on("mouseup", mouseup); function mouse(e) { return [e.pageX - rx, e.pageY - ry]; } function mousedown() { m0 = mouse(d3.event); d3.event.preventDefault(); } function mousemove() { if (m0) { var m1 = mouse(d3.event), dm = Math.atan2(cross(m0, m1), dot(m0, m1)) * 180 / Math.PI; div.style("-webkit-transform", "translateY(" + (ry - rx) + "px)rotateZ(" + dm + "deg)translateY(" + (rx - ry) + "px)"); } } function mouseup() { if (m0) { var m1 = mouse(d3.event), dm = Math.atan2(cross(m0, m1), dot(m0, m1)) * 180 / Math.PI; rotate += dm; if (rotate > 360) rotate -= 360; else if (rotate < 0) rotate += 360; m0 = null; div.style("-webkit-transform", null); svg .attr("transform", "translate(" + rx + "," + ry + ")rotate(" + rotate + ")") .selectAll("g.node text") .attr("dx", function(d) { return (d.x + rotate) % 360 < 180 ? 8 : -8; }) .attr("text-anchor", function(d) { return (d.x + rotate) % 360 < 180 ? "start" : "end"; }) .attr("transform", function(d) { return (d.x + rotate) % 360 < 180 ? null : "rotate(180)"; }); } } function mouseover(d) { svg.selectAll("path.link.target-" + d.key) .classed("target", true) .each(updateNodes("source", true)); svg.selectAll("path.link.source-" + d.key) .classed("source", true) .each(updateNodes("target", true)); } function mouseout(d) { svg.selectAll("path.link.source-" + d.key) .classed("source", false) .each(updateNodes("target", false)); svg.selectAll("path.link.target-" + d.key) .classed("target", false) .each(updateNodes("source", false)); } function updateNodes(name, value) { return function(d) { if (value) this.parentNode.appendChild(this); svg.select("#node-" + d[name].key).classed(name, value); }; } function cross(a, b) { return a[0] * b[1] - a[1] * b[0]; } function dot(a, b) { return a[0] * b[0] + a[1] * b[1]; } ``` -------------------------------- ### Trace specific modules with pycallgraph CLI Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Use the --include flag to filter tracing to specific modules, such as a Django project's core components. This helps in analyzing only relevant parts of a larger codebase. ```bash pycallgraph -v --stdlib --include "django.core.*" graphviz -- ./manage.py migrate --run-syncdb ``` -------------------------------- ### GephiOutput Configuration Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Use GephiOutput to write call graphs to a GDF file, which can be loaded into Gephi for interactive exploration. ```APIDOC ## GephiOutput Writes the call graph to a GDF file that can be loaded into [Gephi](https://gephi.org/) for interactive exploration. ### Configuration Options - `output_file` (str): The name of the output GDF file. Default: 'pycallgraph.gdf'. ### Usage ```python from pycallgraph import PyCallGraph from pycallgraph.output import GephiOutput gephi = GephiOutput(output_file='callgraph.gdf') with PyCallGraph(output=gephi): my_function() # callgraph.gdf contains nodedef and edgedef sections with call counts, timing, memory, and color data ready for Gephi import ``` ``` -------------------------------- ### Profile Scripts with PyCallGraph CLI Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt The `pycallgraph` command-line interface profiles a Python script without code modification. Specify the output type (graphviz or gephi) as a subcommand. ```shell # Basic usage — produces pycallgraph.png pycallgraph graphviz -- ./myscript.py # Custom output filename and format pycallgraph graphviz --output-file=trace.svg --output-format=svg -- ./myscript.py # Pass arguments to the profiled script pycallgraph graphviz --output-file=setup.png -- setup.py --dry-run install # Include stdlib, limit depth, use verbose mode pycallgraph -v --stdlib --max-depth 4 graphviz --output-file=deep.png -- ./myscript.py ``` -------------------------------- ### PyCallGraph Multiple Outputs Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Pass a list of output instances to PyCallGraph to generate multiple output formats in a single trace run. ```APIDOC ## PyCallGraph Multiple Outputs Pass a list of output instances to produce several formats in one trace run. ### Usage ```python from pycallgraph import PyCallGraph from pycallgraph.output import GraphvizOutput, GephiOutput outputs = [ GraphvizOutput(output_file='graph.png'), GephiOutput(output_file='graph.gdf'), ] with PyCallGraph(output=outputs): my_application() ``` ``` -------------------------------- ### Generate Gephi GDF output with pycallgraph CLI Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Generate a graph in GDF format suitable for Gephi by using the 'gephi' command. This is useful for interactive graph analysis. ```bash pycallgraph gephi --output-file=trace.gdf -- ./myscript.py ``` -------------------------------- ### Configure GephiOutput Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Configure GephiOutput to save the call graph in GDF format for import into Gephi. The output file defaults to 'pycallgraph.gdf'. ```python from pycallgraph import PyCallGraph from pycallgraph.output import GephiOutput gephi = GephiOutput(output_file='callgraph.gdf') # default: 'pycallgraph.gdf' with PyCallGraph(output=gephi): my_function() # callgraph.gdf contains nodedef and edgedef sections with call counts, # timing, memory, and color data ready for Gephi import ``` -------------------------------- ### Create Colors with the Color Class Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt The Color class represents RGBA colors for output rendering. It supports RGB and HSV constructors and provides methods for formatting colors into web or CSV formats. ```python from pycallgraph import Color # RGB constructor (alpha defaults to 1.0) red = Color(1, 0, 0) semi_transparent_blue = Color(0, 0, 1, 0.5) # HSV constructor (useful for hue-based gradients) warm = Color.hsv(h=0.05, s=0.8, v=0.9) # orange-ish # Format output print(red.rgb_web()) # '#ff0000' print(red.rgba_web()) # '#ff0000ff' print(red.rgb_csv()) # '255,0,0' ``` -------------------------------- ### Output Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/docs/api/api.md Base class for all output modules in Py-Call-Graph. This provides a foundation for different ways to visualize or store call graph data. ```APIDOC ## Output ### Description Base class for all output modules. This abstract class defines the interface for outputting call graph information. Concrete implementations like `GraphvizOutput` inherit from this. ### Usage Custom output modules can be created by inheriting from this class and implementing the required methods. ``` -------------------------------- ### Customize Node and Edge Colors with Color Functions Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Override `node_color_func` and `edge_color_func` on an output instance to programmatically control graph colors. Functions receive node/edge objects with time and call fractions. ```python from pycallgraph import PyCallGraph, Config, Color from pycallgraph.output import GraphvizOutput def rainbow_node(node): """Color nodes by time fraction across hue spectrum.""" return Color.hsv(node.time.fraction * 0.8, 0.4, 0.9) def greyscale_node(node): """Darker grey = more time spent.""" return Color.hsv(0, 0, node.time.fraction / 2 + 0.4) def constant_black_edge(edge): return Color(0, 0, 0) graphviz = GraphvizOutput(output_file='colored.png') graphviz.node_color_func = rainbow_node graphviz.edge_color_func = constant_black_edge with PyCallGraph(output=graphviz, config=Config(include_stdlib=True)): import re re.compile(r'\d+').findall('abc 123 def 456') ``` -------------------------------- ### Exclude internal helpers and use neato layout with pycallgraph CLI Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt The --exclude flag can be used to ignore internal helper modules during tracing. The --tool=neato option specifies the layout engine for the graph visualization. ```bash pycallgraph --exclude "myapp.helpers.*" graphviz --tool=neato --output-file=neato.png -- ./app.py ``` -------------------------------- ### Use PyCallGraph as a Context Manager Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Trace function calls within a block of code using PyCallGraph as a context manager. The graph is automatically generated upon exiting the block. ```python from pycallgraph import PyCallGraph from pycallgraph.output import GraphvizOutput graphviz = GraphvizOutput() graphviz.output_file = 'mygraph.png' with PyCallGraph(output=graphviz): # All calls inside this block are traced result = my_function() # mygraph.png is generated automatically on exit ``` -------------------------------- ### Limit Call Depth to 1 Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/docs/guide/filtering.md Sets the maximum call depth to 1 using config.max_depth. This limits the graph to only show the immediate calls made by the entry point, useful for understanding top-level interactions. ```python #!/usr/bin/env python from pycallgraph import PyCallGraph from pycallgraph import Config from pycallgraph.output import GraphvizOutput from banana import Banana config = Config(max_depth=1) graphviz = GraphvizOutput(output_file='filter_max_depth.png') with PyCallGraph(output=graphviz, config=config): banana = Banana() banana.eat() ``` -------------------------------- ### @trace Decorator Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt The pycallgraph.decorators.trace decorator wraps a single function, generating a fresh call graph for each invocation. ```APIDOC ## @trace Decorator `pycallgraph.decorators.trace` wraps a single function so that every call to it produces a fresh call graph. ### Usage ```python from pycallgraph import Config from pycallgraph import decorators as pycallgraph from pycallgraph.output import GraphvizOutput graphviz = GraphvizOutput(output_file='decorated.png') @pycallgraph.trace(output=graphviz, config=Config()) def process_data(items): return [item * 2 for item in items] # Each invocation automatically traces and generates output process_data(range(100)) ``` ``` -------------------------------- ### Measure Without Filtering Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/docs/guide/filtering.md Measures the execution of the Banana class's eat method without any filtering. This provides a baseline for comparison. ```python #!/usr/bin/env python from pycallgraph import PyCallGraph from pycallgraph.output import GraphvizOutput from banana import Banana graphviz = GraphvizOutput(output_file='filter_none.png') with PyCallGraph(output=graphviz): banana = Banana() banana.eat() ``` -------------------------------- ### PyCallGraph Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/docs/api/api.md The main interface for interacting with the Python Call Graph functionality. This class allows users to generate and manage call graphs. ```APIDOC ## PyCallGraph ### Description Main interface to Python Call Graph. This class is the primary entry point for users to generate and manipulate call graphs. ### Usage ```python from pycallgraph import PyCallGraph from pycallgraph.output import GraphvizOutput with PyCallGraph(outputter=GraphvizOutput()): # Code to be profiled my_function() ``` ``` -------------------------------- ### Trace a Single Function with @trace Decorator Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Use the @trace decorator to wrap a specific function, generating a new call graph for each invocation of that function. ```python from pycallgraph import Config from pycallgraph import decorators as pycallgraph from pycallgraph.output import GraphvizOutput graphviz = GraphvizOutput(output_file='decorated.png') @pycallgraph.trace(output=graphviz, config=Config()) def process_data(items): return [item * 2 for item in items] # Each invocation automatically traces and generates output process_data(range(100)) ``` -------------------------------- ### GlobbingFilter Class Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/docs/api/globbing_filter.md The `GlobbingFilter` class is used for filtering methods based on glob patterns. It allows users to specify patterns to include or exclude methods from a list. ```APIDOC ## Class: `GlobbingFilter` ### Description This class is designed to filter methods using glob patterns. It supports both inclusion and exclusion of methods based on specified patterns. ### Usage Instantiate the `GlobbingFilter` with inclusion and exclusion patterns. The `filter` method can then be used to apply these patterns to a list of method names. ```python from py_call_graph.globbing_filter import GlobbingFilter # Example usage: include_patterns = ['my_module.*', 'another_module.specific_function'] exclude_patterns = ['my_module.internal_*'] filterer = GlobbingFilter(include_patterns, exclude_patterns) methods_to_filter = [ 'my_module.public_function', 'my_module.internal_helper', 'another_module.specific_function', 'third_module.some_function' ] filtered_methods = filterer.filter(methods_to_filter) print(filtered_methods) # Expected output: ['my_module.public_function', 'another_module.specific_function'] ``` ### Methods #### `__init__(self, include_patterns: list[str], exclude_patterns: list[str])` Initializes the `GlobbingFilter` with lists of include and exclude glob patterns. - **include_patterns** (list[str]) - A list of glob patterns for methods to include. - **exclude_patterns** (list[str]) - A list of glob patterns for methods to exclude. #### `filter(self, methods: list[str]) -> list[str]` Filters a given list of method names based on the configured include and exclude patterns. - **methods** (list[str]) - The list of method names to filter. - **Returns** (list[str]) - A new list containing only the methods that match the filter criteria. ``` -------------------------------- ### Banana Class Definition Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/docs/guide/filtering.md Defines a simple Banana class with methods for eating, including secret_function, chew, and swallow. This class is used to demonstrate filtering. ```python import time class Banana: def __init__(self): pass def eat(self): self.secret_function() self.chew() self.swallow() def secret_function(self): time.sleep(0.2) def chew(self): pass def swallow(self): pass ``` -------------------------------- ### Disable module grouping with pycallgraph CLI Source: https://context7.com/lewiscowles1986/py-call-graph/llms.txt Use the --no-groups flag to disable the default module grouping in the call graph visualization. This can provide a flatter, more detailed view of function calls. ```bash pycallgraph --no-groups graphviz -- ./myscript.py ``` -------------------------------- ### Exclude Secret Functions and PyCallGraph Internals Source: https://github.com/lewiscowles1986/py-call-graph/blob/main/docs/guide/filtering.md Uses a GlobbingFilter to exclude 'secret_function' and internal 'pycallgraph' calls from the generated graph. This helps to declutter the output by hiding implementation details. ```python #!/usr/bin/env python from pycallgraph import PyCallGraph from pycallgraph import Config from pycallgraph import GlobbingFilter from pycallgraph.output import GraphvizOutput from banana import Banana config = Config() config.trace_filter = GlobbingFilter(exclude=[ 'pycallgraph.*', '*.secret_function', ]) graphviz = GraphvizOutput(output_file='filter_exclude.png') with PyCallGraph(output=graphviz, config=config): banana = Banana() banana.eat() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.