在 Python 中,在不使用 traceback
模块的情况下,有没有办法从该函数中确定函数的名称?
假设我有一个带有函数 bar
的模块 foo
。执行foo.bar()
时,有没有办法让bar
知道bar
的名字?或者更好的是,foo.bar
的名字?
#foo.py
def bar():
print "my name is", __myname__ # <== how do I calculate this at runtime?
最佳答案
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()
输出:
foo <module_caller_of_foo>
关于python - 从该函数中确定函数名称(不使用回溯),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5067604/