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.

user739807
  • 855
  • 4
  • 9
  • 14

4 Answers4

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.

saaj
  • 23,253
  • 3
  • 104
  • 105
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.

argentpepper
  • 4,202
  • 3
  • 33
  • 45
KushalP
  • 10,976
  • 6
  • 34
  • 27
  • Maybe this: http://doc.pypy.org/en/latest/objspace.html#the-flow-model and http://doc.pypy.org/en/release-2.0-beta2/translation.html#the-annotation-pass – slashdottir Feb 19 '14 at 16:46
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

-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.

anatoly techtonik
  • 19,847
  • 9
  • 124
  • 140
  • 3
    The question asks about the [Control Flow Graph](http://en.wikipedia.org/wiki/Control_flow_graph), not the [Call Graph](http://en.wikipedia.org/wiki/Call_graph). – 0 _ Sep 28 '13 at 08:03
  • 1
    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. – anatoly techtonik Sep 28 '13 at 09:03
  • @johntex, concerning the question of comparing two methods. What do you things about [using AST hashes](https://groups.google.com/forum/#!topic/python-ideas/GWqOddowZ5c) for that? – anatoly techtonik Sep 28 '13 at 09:04