pythonfunctioncall-graph

Building a call tree for a Python code


I've been given a Python code, together with the modules it imports. I would like to build a tree indicating which function calls what other functions. How can I do that?


Solution

  • you can use the ast (abstract syntax tree) module from the python standard library

    # foo.py
    def func(x):
        print('hello')
    

    parsing the file using ast.parse:

    import ast
    tree = ast.parse(open('foo.py').read())
    print(ast.dump(tree))  # dumps the whole tree
    
    # get the function from the tree body (i.e. from the file's content)
    func = tree.body[0]
    
    # get the function argument names
    arguments = [a.arg for a in func.args.args]
    print('the functions is: %s(%s)' % (func.name, ', '.join(arguments)))
    

    outputs:

    "Module(body=[FunctionDef(name='func', args=arguments(args=[arg(arg='x', annotation=None)], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[]), body=[Expr(value=Call(func=Name(id='print', ctx=Load()), args=[Str(s='hello')], keywords=[]))], decorator_list=[], returns=None)])"
    
    the functions is: func(x)