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

def foo():
    pass

>>> name_of(foo)
"foo"

当前回答

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

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

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

其他回答

我喜欢使用函数装饰器。 我添加了一个类,它也乘以函数时间。假设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():

你只需要知道函数的名字这是一个简单的代码。 假设你已经定义了这些函数

def function1():
    print "function1"

def function2():
    print "function2"

def function3():
    print "function3"
print function1.__name__

输出将是function1

现在假设你有一个列表中的这些函数

a = [function1 , function2 , funciton3]

来获取函数的名称

for i in a:
    print i.__name__

输出将是

function1 function2 function3

要从函数或方法中获取当前函数或方法的名称,考虑:

import inspect

this_function_name = inspect.currentframe().f_code.co_name

sys。_getframe也可以代替inspect。虽然后者避免访问私有函数。

要获得调用函数的名称,请考虑inspect.currentframe().f_back.f_code.co_name中的f_back。


如果也使用mypy,它可以抱怨:

选项"Optional[FrameType]"中的"None"没有属性"f_code"

为了抑制上述错误,考虑:

import inspect
import types
from typing import cast

this_function_name = cast(types.FrameType, inspect.currentframe()).f_code.co_name

Try

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

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

import inspect

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

在哪里

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