5

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?

0

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

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

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.