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

4

21

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.

Quianaquibble answered 1/6, 2011 at 16:59 Comment(1)
bytecode.readthedocs.io/en/latest/cfg.htmlCroquette
H
9

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')

quick sort

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

Heterotaxis answered 26/11, 2020 at 20:27 Comment(0)
C
7

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.

Costume answered 1/6, 2011 at 17:9 Comment(1)
E
2

I found py2cfg has a better representation of Control Flow Graph (CFG) than one from staticfg.

Let's take this function in Python:

    def fib():
        a, b = 0, 1
        while True:
            yield a
            a, b = b, a + b

    fib_gen = fib()
    for _ in range(10):
        next(fib_gen)

Image from StaticCFG: enter image description here

Image from PY2CFG: enter image description here

Epileptoid answered 13/6, 2022 at 8:17 Comment(0)
M
-1

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.

Mislay answered 6/6, 2012 at 16:42 Comment(3)
The question asks about the Control Flow Graph, not the Call Graph.Lazare
Accepted. 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.Mislay
@johntex, concerning the question of comparing two methods. What do you things about using AST hashes for that?Mislay

© 2022 - 2025 — McMap. All rights reserved.