在Python中,如果不使用traceback模块,是否有一种方法可以从函数内部确定函数的名称?
假设我有一个模块foo和一个功能栏。当执行foo.bar()时,是否有一种方法让bar知道bar的名字?或者更好的是,foo。酒吧的名字吗?
#foo.py
def bar():
print "my name is", __myname__ # <== how do I calculate this at runtime?
在Python中,如果不使用traceback模块,是否有一种方法可以从函数内部确定函数的名称?
假设我有一个模块foo和一个功能栏。当执行foo.bar()时,是否有一种方法让bar知道bar的名字?或者更好的是,foo。酒吧的名字吗?
#foo.py
def bar():
print "my name is", __myname__ # <== how do I calculate this at runtime?
当前回答
这实际上是由这个问题的其他答案推导出来的。
以下是我的看法:
import sys
# for current func name, specify 0 or no argument.
# for name of caller of current func, specify 1.
# for name of caller of caller of current func, specify 2. etc.
currentFuncName = lambda n=0: sys._getframe(n + 1).f_code.co_name
def testFunction():
print "You are in function:", currentFuncName()
print "This function's caller was:", currentFuncName(1)
def invokeTest():
testFunction()
invokeTest()
# end of file
与使用inspect.stack()相比,这个版本可能的优势是它应该快数千倍[参见Alex Melihoff关于使用sys._getframe()与使用inspect.stack()的文章和计时]。
其他回答
functionNameAsString = sys._getframe().f_code.co_name
我想要一个非常相似的东西,因为我想把函数名放在一个log字符串中,在我的代码中有很多地方。可能不是最好的方法,但这里有一种获取当前函数名称的方法。
str(str(inspect.currentframe())).split(' ')[-1][:-1]
print(inspect.stack()[0].function)似乎也可以工作(Python 3.5)。
import inspect
def foo():
print(inspect.stack()[0][3])
print(inspect.stack()[1][3]) # will give the caller of foos name, if something called foo
foo()
输出:
喷火 < module_caller_of_foo >
Python没有在函数本身中访问函数或其名称的特性。它已经被提出,但被否决了。如果你不想自己玩堆栈,你应该使用“bar”或bar。__name__取决于上下文。
给定的拒绝通知为:
此PEP被拒绝。它不清楚应该如何实现,也不清楚在边缘情况下应该有什么精确的语义,而且没有给出足够重要的用例。人们的反应充其量也只是不温不火。