You can print all call expressions with:
import ast class CallCollector(ast.NodeVisitor): def __init__(self): self.calls = [] self.current = None def visit_Call(self, node):
Use this with the ast parsing tree:
tree = ast.parse(yoursource) cc = CallCollector() cc.visit(tree) print cc.calls
Demo:
>>> tree = ast.parse('''\ ... def foo(): ... print np.random.rand(4) + np.random.randn(4) ... print linalg.norm(np.random.rand(4)) ... ''') >>> cc = CallCollector() >>> cc.visit(tree) >>> cc.calls ['np.random.rand', 'np.random.randn', 'linalg.norm']
The above walker only processes names and attributes; if you need more sophisticated expression support, you will have to extend this.
Note that collecting names like this is not a trivial task . Any feedback will not be processed. You can create a dictionary in your function code to call and dynamically replace function objects, and static analysis like the one above cannot track it.
source share