我如何得到一个函数的名字作为字符串?

def foo():
    pass

>>> name_of(foo)
"foo"

当前回答

Try

import sys
fn_name = sys._getframe().f_code.co_name

进一步的参考 https://www.oreilly.com/library/view/python-cookbook/0596001673/ch14s08.html

其他回答

my_function.func_name

函数还有其他有趣的属性。输入dir(func_name)来列出它们。func_name.func_code。Co_code是编译后的函数,存储为字符串。

import dis
dis.dis(my_function)

将以几乎人类可读的格式显示代码。:)

该函数将返回调用方的函数名。

def func_name():
    import traceback
    return traceback.extract_stack(None, 2)[0][2]

这就像Albert Vonpupp用友好的包装给出的答案。

你可以通过使用特殊的__name__变量来获取一个字符串形式的函数名。

def my_function():
    pass

print(my_function.__name__) # prints "my_function"

我喜欢使用函数装饰器。 我添加了一个类,它也乘以函数时间。假设gLog是一个标准的python记录器:

class EnterExitLog():
    def __init__(self, funcName):
        self.funcName = funcName

    def __enter__(self):
        gLog.debug('Started: %s' % self.funcName)
        self.init_time = datetime.datetime.now()
        return self

    def __exit__(self, type, value, tb):
        gLog.debug('Finished: %s in: %s seconds' % (self.funcName, datetime.datetime.now() - self.init_time))

def func_timer_decorator(func):
    def func_wrapper(*args, **kwargs):
        with EnterExitLog(func.__name__):
            return func(*args, **kwargs)

    return func_wrapper

现在你要做的就是装饰它,瞧

@func_timer_decorator
def my_func():
import inspect

def foo():
   print(inspect.stack()[0][3])

在哪里

Stack()[0]是调用者 [3]是方法的字符串名称