如何获取调用函数或方法的人?

时间:2013-12-20 14:21:06

标签: python reflection introspection

这就是我需要的:

def get_invoker():
    # your magic here

# invoker.py    

def f():
    invoker = get_invoker()
    print(invoker)


# module1.py
class C(object):
    def invoke_f(self):
        f()


f()
# print <module1>

c = C()
c.invoke_f()
# print C.invoke_f

有可能吗?我知道模块inspect具有所有这些魔力,但我无法找到它。

修改

我想获取函数对象(或模块)。不只是名字。

1 个答案:

答案 0 :(得分:1)

像这样:

>>> import inspect
>>> def called_function():
...     print inspect.stack()[1][3]
...
>>> def caller():
...     called_function()
...
>>> caller()
caller