在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?
当前回答
print(inspect.stack()[0].function)似乎也可以工作(Python 3.5)。
其他回答
import sys
def func_name():
"""
:return: name of caller
"""
return sys._getframe(1).f_code.co_name
class A(object):
def __init__(self):
pass
def test_class_func_name(self):
print(func_name())
def test_func_name():
print(func_name())
测试:
a = A()
a.test_class_func_name()
test_func_name()
输出:
test_class_func_name
test_func_name
你可以使用@Andreas Jung显示的方法获得它定义时的名称,但这可能不是调用函数时的名称:
import inspect
def Foo():
print inspect.stack()[0][3]
Foo2 = Foo
>>> Foo()
Foo
>>> Foo2()
Foo
这种区别对你来说是否重要,我不能说。
print(inspect.stack()[0].function)似乎也可以工作(Python 3.5)。
实现您自己的装饰器
# mydecorators.py
def resolve_function(func):
#in case annotated func is an staticmethod
if isinstance(func,staticmethod):
return func.__func__
return func
def print_my_name(func):
def function_caller(*args,**kwargs):
_func = resolve_function(func)
print("my name is: %s" %_func.__name__)
return _func(*args,**kwargs)
return function_caller
然后使用它
# foo.py
from mydecorators import *
@print_my_name
def bar():
#do something else
#in terminal: my name is: bar
import inspect
def method_name():
return inspect.stack()[1][3]
def method_name_caller():
return inspect.stack()[2][3]
def asdf():
print(method_name_caller())
print(method_name())
def asdf2():
print(method_name_caller())
print(method_name())
asdf()