Using pythons inspect
module I have isolated a method object, I now need to step through the source code in the method to find calls to certain other methods and get their arguments.
For example, suppose in the following class:
def my_method():
print('hello')
foobar('apple', 'pear', 6)
print('world')
foobar(1, 2, 3)
return foobar('a', 'b')
I need to extract a list of arguments passed to foobar()
:
[('apple', 'pear', 6), (1, 2, 3), ('a', 'b', None)]
It can be assumed all arguments are hard coded and not dynamic.
Given a method object from the inspect
package, how can I inspect the method calls in said method?
Attempts
- I've tried using regexes with
inspect.getsourcelines(method)
but this breaks if the argument syntax changes. - I've looked into abstract syntax trees with pythons
ast
module but havn't come to any solution. - There must be a way to complete this using
inspect
but again I havn't come to any solution.
This is not perfect but should be a start, I will add a better implementation in a bit:
test.py looks like:
If you had a mixture of both you would need to combine somehow changing the call after
print('world')
tofoobar(a=1, b=2, c=3)
Output:
Using the ast.Nodevisitor to find all Call objects will return all calls to "foobar" in all functions:
Output:
You can again add a search for kwargs and only search the specific functions.