Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all the functions that has been *used* in a python script?

Tags:

python

Say I have a python script in this form

import numpy as np
x = [1, 2, 5, 3, 9, 6]
x.sort()
print(np.sum(x))

I want to extract all the functions that have been used in this script. For this example the outcome should be list.sort, np.sum, print. I can list all the builtin functions and then expand that list with dir(numpy). And then check whether each of those functions appear in the code.

But what if there is a function like np.linalg.norm(x)? How will I find this function since norm will not be returned by dir(numpy).

Note: I understand many other functions can be invoked which does not appear in the code. For this example list.__init__. But I only want those functions that appears in the code. Simply put, I want all the words/tokens that will be colored yellow by vscode in Dark+ theme. Is there any possible way to use rope for this problem?

like image 1000
Pritam Avatar asked Oct 27 '25 08:10

Pritam


1 Answers

You can use ast module to do something like that:

import ast


code = """
import numpy as np
x = [1, 2, 5, 3, 9, 6]
x.sort()
print(np.sum(x))
"""

module = ast.parse(code)

for node in ast.walk(module):
    if isinstance(node, ast.Call):
        try:
            parent_name = node.func.value.id + '.'
        except AttributeError:
            parent_name = ''
        if isinstance(node.func, ast.Name):
            print(f'{parent_name}{node.func.id}')
        else:
            print(f'{parent_name}{node.func.attr}')

# output:
#  x.sort
#  print
#  np.sum

Of course, there is x.sort instead of list.sort but I didn't find out how to get the actual parent type of the method.

like image 102
Mohammad Jafari Avatar answered Oct 28 '25 22:10

Mohammad Jafari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!