问题
What is the best way to find all function calls that a function makes? I want to do this at runtime (likely with a decorator).
Is the best way to retrieve the source code with inspect
(this means that I will have to have access to the source code...so no interactive interpreter support) and then parse it with ast
? Is there a better way?
Python 2.7 preferred, but not required. I'd like it to be simple enough to do myself. If others have done it, I would look at the source code so I could figure it out.
Ultimately, I will only be interested in calls to functions with a particular decorator, but there are already answers to that part on SO.
Edit:
def f():
return g(1)
@Interesting
def g(x):
return x + 1
print what_interesting_functions_does_this_call(f)
prints
(<function g at 0x7f2a1ec72a28>,)
I realize now that because of how dynamic Python is, this is not possible in the general case. But could I cover some subset of cases?
FYI: "You are an idiot and why would you ever think to be able to tell what functions are called by another function and I can't think of any reason why this would ever be useful, therefore it must not be useful for you" is an okay response. I would like to know.
回答1:
>>> def a():
... float("1.2")
... int("1")
... b()
...
>>> def b():
... sum([1,2,3])
...
>>> a()
>>> import dis
>>> dis
<module 'dis' from 'C:\Python26\lib\dis.pyc'>
>>> dis.dis(a)
2 0 LOAD_GLOBAL 0 (float)
3 LOAD_CONST 1 ('1.2')
6 CALL_FUNCTION 1
9 POP_TOP
3 10 LOAD_GLOBAL 1 (int)
13 LOAD_CONST 2 ('1')
16 CALL_FUNCTION 1
19 POP_TOP
4 20 LOAD_GLOBAL 2 (b)
23 CALL_FUNCTION 0
26 POP_TOP
27 LOAD_CONST 0 (None)
30 RETURN_VALUE
>>>
you could just count the "CALL_FUNCTION" ...
in general I dont think you want to do something like this in production code ...
来源:https://stackoverflow.com/questions/16042005/find-all-function-calls-by-a-function