在Python中,如果不使用traceback模块,是否有一种方法可以从函数内部确定函数的名称?

假设我有一个模块foo和一个功能栏。当执行foo.bar()时,是否有一种方法让bar知道bar的名字?或者更好的是,foo。酒吧的名字吗?

#foo.py  
def bar():
    print "my name is", __myname__ # <== how do I calculate this at runtime?

当前回答

这是一个经得起考验的方法。

将@CamHart和@Yuval的建议与@RoshOxymoron接受的答案结合起来,可以避免:

_hidden和潜在弃用的方法 在堆栈中建立索引(可以在未来的python中重新排序)

所以我认为这对未来的python版本(在2.7.3和3.3.2测试)很有帮助:

from __future__ import print_function
import inspect

def bar():
    print("my name is '{}'".format(inspect.currentframe().f_code.co_name))

更新:在3.7.10,3.8.10和3.9.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 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 >

我找到了一个包装器,它将写入函数名

from functools import wraps

def tmp_wrap(func):
    @wraps(func)
    def tmp(*args, **kwargs):
        print func.__name__
        return func(*args, **kwargs)
    return tmp

@tmp_wrap
def my_funky_name():
    print "STUB"

my_funky_name()

这将打印

my_funky_name 存根

str(str(inspect.currentframe())).split(' ')[-1][:-1]

我最近尝试使用上面的答案从该函数的上下文中访问函数的文档字符串,但由于上面的问题只返回名称字符串,因此不起作用。

幸运的是,我找到了一个简单的解决办法。如果像我一样,想要引用函数,而不是简单地获取表示名称的字符串,那么可以对函数名称的字符串应用eval()。

import sys
def foo():
    """foo docstring"""
    print(eval(sys._getframe().f_code.co_name).__doc__)