PyCG - Practical Python Call Graphs

raw JSON →
0.0.8 verified Fri May 01 auth: no python maintenance

PyCG is a tool for generating call graphs for Python code using static analysis. It produces call graphs in JSON format and supports Python >=3.4. The current version on PyPI is 0.0.8. Development is relatively low activity; last commits on GitHub appear to be from 2022. The primary use case is understanding static call relationships in Python programs.

pip install pycg
error ModuleNotFoundError: No module named 'pycg'
cause PyCG is not installed, or installed in a different environment.
fix
Run pip install pycg in your current environment. Ensure you are using the same Python interpreter.
error TypeError: __init__() missing 1 required positional argument: 'package_name'
cause The CallGraphGenerator constructor requires a package name as the second argument.
fix
Change CallGraphGenerator([file]) to CallGraphGenerator([file], 'my_package_name').
error KeyError: 'caller' (when accessing output)
cause The output format may have changed; accessing raw generator data instead of using the formatter.
fix
Use formats.JSONFormatter(generator).generate() to get a properly formatted JSON object.
gotcha PyCG requires the second argument to be the package/module name (e.g., 'mymodule'), not just a label. Mistakenly using a file path or empty string can cause unexpected behavior or empty output.
fix Pass the module name (the name you would use in imports, e.g., 'myscript' for myscript.py).
gotcha PyCG only analyzes the statically visible call graph; it does not resolve dynamic calls (e.g., through eval, getattr, or decorators that obscure call sites). Results may be incomplete for heavily dynamic code.
fix Use pycg as a supplementary tool; combine with runtime tracing for full coverage.
deprecated PyCG has not been actively maintained since 2022. There are known issues with Python 3.10+ regarding changes to the ast module. The project may not work correctly with newer Python versions.
fix Consider using alternatives like `pyan` or `code2flow` for better Python 3.10+ support.

Basic usage to generate a JSON call graph for a Python file. Note that pycg expects a list of file paths and a package name.

from pycg import CallGraphGenerator
from pycg import formats

# Example: generate call graph for a single file
# Note: pycg works best with a top-level script entry point
# For this example, we'll assume you have a file 'myscript.py'
# that defines functions and calls.
# The generator returns a dictionary of call edges.

generator = CallGraphGenerator(['myscript.py'], 'myscript')
# The second argument is the package name (usually module name)
generator.analyze()

# Get call graph in JSON format
formatter = formats.JSONFormatter(generator)
output = formatter.generate()
print(output)