如何在Python中获取另一个函数内的调用者函数名?
如果你有两个函数,比如:
def A
def B
然后函数A调用了函数B,你能在函数B里面知道是谁在调用它吗,像这样:
def A () :
B ()
def B () :
this.caller.name
相关问题:
5 个回答
17
注意(2018年6月):今天我可能会使用 inspect 模块,看看其他的回答
sys._getframe(1).f_code.co_name 就像下面的例子:
>>> def foo():
... global x
... x = sys._getframe(1)
...
>>> def y(): foo()
...
>>> y()
>>> x.f_code.co_name
'y'
>>>
重要提示:从 _getframe 这个方法的名字就能看出来(嘿,它是以一个下划线开头的),这不是一个应该盲目依赖的API方法。
39
有两种方法可以做到这一点,分别是使用 sys 模块和 inspect 模块:
sys._getframe(1).f_code.co_nameinspect.stack()[1][3]
第二种方法 stack() 的可读性较差,而且它的实现依赖性较强,因为它调用了 sys._getframe()。下面是 inspect.py 的一段摘录:
def stack(context=1):
"""Return a list of records for the stack above the caller's frame."""
return getouterframes(sys._getframe(1), context)
281
你可以使用 inspect 模块来获取你想要的信息。它的 stack 方法会返回一个帧记录的列表。
对于 Python 2,每个帧记录是一个列表。每个记录的第三个元素是调用者的名字。你需要的就是这个:
>>> import inspect >>> def f(): ... print inspect.stack()[1][3] ... >>> def g(): ... f() ... >>> g() g
对于 Python 3.5+,每个帧记录是一个 命名元组,所以你需要把
print inspect.stack()[1][3]替换成
print(inspect.stack()[1].function)在上面的代码中。