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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With