How to find all function calls a defined function makes? (including recursive and futher down the stack calls)

44 Views Asked by At

I'm using Python's AST module, and stuck on a given problem (it may be that AST isn't the right tool for this problem).

I want to determine if a given function (let's say "print" as an example) is called, by a defined function.

For example:

file_one.py

def some_function():
    print("hello!")

file_two.py

from file_one import some_function

def one():
    print("hi!")

def two():
    one()

def three():
    some_function()

def four():
    three()

How can I parse file_two.py and figure out which functions (in this case all of them) call print?

At the moment, I have something like this:

import ast

class Visitor(ast.NodeVisitor):
    def visit_FunctionDef(self, node: ast.AST):
        for child in ast.walk(node):
            if isisntance(child, ast.Call) and child.func.id == "print":
                print(f"Found a function that calls print!")

if __name__ == "__main__":
    with open("file_two.py") as file:
        tree = ast.parse(file.read())
    Visitor().visit(tree)

But this only works for the function file_two.one and no others.

0

There are 0 best solutions below