Automatically generate function call graphs for Python code.
graph.py is a Python script that analyzes Python source code and generates visual function call graphs showing dependencies between functions.
- Supports Python
- Configurable graph generation
- Interactive visualization with matplotlib
- Unit tested with sample code cases
Create a file containing your Python source code. For example, you can combine multiple Python files into a single input file:
find ./src/ -name '*.py' -exec cat {} \; > input.txtor
cat ./src/*.py > input.txtRun the script:
python3 graph.pyA window will display the interactive graph. You can zoom, pan, and inspect nodes.
Modify the generator's configuration before generating the graph:
generator = CallGraphGenerator()
generator.config["allow_external_funcs"] = False # Exclude functions called but not defined in the source
generator.config["allow_self_reference"] = False # Hide recursive calls
generator.config["allow_childless_funcs"] = False # Omit functions that do not call other functions
generator.generate_call_graph("input.txt")| Setting | Default | Description |
|---|---|---|
allow_external_funcs |
True | Show functions called but not defined in the source |
allow_self_reference |
True | Display edges for recursive calls |
allow_childless_funcs |
True | Include functions that don't call other functions |
Unit tests verify function extraction and graph generation. Run tests with:
python3 -m unittest test.py- Python 3.6+
- networkx
- matplotlib
Install requirements:
pip install --user networkx matplotlib-
Language Detection: Checks the first 10 lines for the Python-specific pattern:
- Python:
defkeywords at the beginning of a line (allowing for leading spaces).
- Python:
-
Parsing: The Python parser extracts function definitions and calls.
-
Graph Construction: Uses networkx to build a directed graph from call relationships.
-
Visualization: Applies the spring layout algorithm and matplotlib for interactive display.
- For large codebases, consider splitting into modules. The script processes all input as a single file.
- The spring layout's appearance can be adjusted in
create_and_visualize_graph(). - Function detection uses basic pattern matching. Complex syntax may require parser improvements.
Interact with the graph to:
- Drag nodes to rearrange the layout
- Zoom with the scroll wheel
- Click nodes to highlight connections