Building a call tree for a Python code

5.6k views Asked by At

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?

2

There are 2 answers

3
ShmulikA On BEST ANSWER

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)
0
Daniyal Ahmed On

You should begin from the main function of the program and at the first layer link all functions that are called from the main this would provide a start point and then you can link all the functions below it.