查找一个函数的所有函数调用 [英] Find all function calls by a function
问题描述
找到一个函数进行的所有函数调用的最佳方法是什么?我想在运行时执行此操作(可能使用装饰器).
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).
是使用 inspect
检索源代码的最佳方法(这意味着我将不得不访问源代码...因此没有交互式解释器支持),然后使用 ast
?有更好的方法吗?
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是首选,但不是必需的.我希望它足够简单,自己动手做.如果其他人做到了,我将看一下源代码,以便找出答案.
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.
最终,我只会对使用特定装饰器的函数感兴趣,但是在SO上已经有该部分的答案.
Ultimately, I will only be interested in calls to functions with a particular decorator, but there are already answers to that part on SO.
def f():
return g(1)
@Interesting
def g(x):
return x + 1
print what_interesting_functions_does_this_call(f)
打印
(<function g at 0x7f2a1ec72a28>,)
我现在意识到,由于Python的动态性,在一般情况下这是不可能的.但是我可以涵盖部分案例吗?
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:您是个白痴,为什么您曾经想过能够说出另一个功能调用了什么功能,而我却想不出为什么这个功能会有用,所以它一定不会有用为您"是一个不错的回答.我想知道.
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.
推荐答案
>>> 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
>>>
您可以只计算"CALL_FUNCTION" ...
you could just count the "CALL_FUNCTION" ...
总的来说,我不认为您想在生产代码中做类似的事情……
in general I dont think you want to do something like this in production code ...
这篇关于查找一个函数的所有函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!