What is the easiest way to generate a Control Flow-Graph for a method in Python?
Solution 1
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 CFGBuilder
cfg = CFGBuilder().build_from_file('quick sort', 'qsort.py')
cfg.build_visual('qsort', 'png')
Note that it doesn't seem to understand more advanced control flow like comprehensions.
Solution 2
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.
Related videos on Youtube
user739807
Updated on June 04, 2022Comments
-
user739807 almost 2 years
I am writing a program that tries to compare two methods. I would like to generate Control flow graphs (CFG) for all matched methods and use either a topological sort to compare the two graphs.
-
Valentin Lorentz almost 8 years
-
-
0 _ over 10 yearsThe question asks about the Control Flow Graph, not the Call Graph.
-
anatoly techtonik over 10 yearsAccepted. Is Call Graph a subset of CFG? Wikipedia is silent about relationship between each other. I thought that you can build CG from filtered CFG.
-
anatoly techtonik over 10 years@johntex, concerning the question of comparing two methods. What do you things about using AST hashes for that?
-
slashdottir about 10 years