Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all references of a specific function definition in Python

I am interested in finding (in the form of line and column position and value) all references where a specific function has been called inside a Python sourcefile.

I have looked into the ast module and these docs but I have not found a way to achieve my goal. All I am able to do is find the nodes of function definitions and of every call.

Does anyone know how to achieve on getting the references of a specific function? Ideally, I would like to do the same for classes as well.


1 Answers

<`# this should get you the functions import ast  

def get_function(node):  
    for stmt in node.body:  
        if isinstance(stmt, ast.FunctionDef):  
            print('This is a Function: {}'.format(stmt.name))  
        elif isinstance(node, ast.ClassDef):  
            print('This is a Class: {}'.format(stmt.name))  

if __name__ == '__main__()':  
    with open('/examples/filename.py').read() as data:  
        tree = ast.parse(data)  
        get_function(tree)  

#I believe this should help.>

like image 103
Samaila Leeman Avatar answered Dec 09 '25 14:12

Samaila Leeman