在python中获取函数调用者的信息

iTa*_*ayb 8 python callstack introspection

我想获得有关python中特定函数的调用者的信息.例如:

class SomeClass():
    def __init__(self, x):
        self.x = x
    def caller(self):
        return special_func(self.x)

def special_func(x):
    print "My caller is the 'caller' function in an 'SomeClass' class."
Run Code Online (Sandbox Code Playgroud)

有可能与python?

Mar*_*ers 11

是的,该sys._getframe()函数允许您从当前执行堆栈中检索帧,然后可以使用inspect模块中的方法和文档进行检查; 您将在f_locals属性中查找特定的本地人以及f_code信息:

import sys
def special_func(x):
    callingframe = sys._getframe(1)
    print 'My caller is the %r function in a %r class' % (
        callingframe.f_code.co_name, 
        callingframe.f_locals['self'].__class__.__name__)
Run Code Online (Sandbox Code Playgroud)

请注意,您需要注意检测每个帧中找到的信息类型.

  • 来自文档:"不保证在Python的所有实现中都存在." (2认同)