What is the easiest way to generate a Control Flow-Graph for a method in Python? What is the easiest way to generate a Control Flow-Graph for a method in Python? python python

What is the easiest way to generate a Control Flow-Graph for a method in Python?


RPython, the translation toolchain behind PyPy, offers a way of grabbing the flow graph (in the pypy/rpython/flowspace directory of the PyPy project) for type inference.

This works quite well in most cases but generators are not supported. The result will be in SSA form, which might be good or bad, depending on what you want.


There's a Python package called staticfg which does exactly the this -- generation of control flow graphs from a piece of Python code.

For instance, putting the first quick sort Python snippet from Rosseta Code in qsort.py, the following code generates its control flow graph.

from staticfg import CFGBuildercfg = CFGBuilder().build_from_file('quick sort', 'qsort.py')cfg.build_visual('qsort', 'png')

quick sort

Note that it doesn't seem to understand more advanced control flow like comprehensions.


http://pycallgraph.slowchop.com/ looks like what you need.

Python trace module also have option --trackcalls that can be an entrypoint for call tracing machinery in stdlib.