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 Answers
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)
3 Comments
DeltaIV
Looks interesting! I'm not sure how to use it, though. If tomorrow I modify my question adding a minimal example, could you show me how to use
ast to build the corresponding call tree?DeltaIV
Hmm, the output seems too verbose to be of any help. It seems to include also all the statements inside each function, not just the calls. On a code thousand lines long, with numerous dependencies, I don't think it will generate usable output. Is it possible to limit the output to the function calls? Tomorrow I'll add a minimal example, with input and desired output.
ShmulikA
the
ast.dump(tree) only prints nicely the tree for debugging proposes. you can access the tree members and attributes. I added example of getting the function name and arguments