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

def foo():
    pass

>>> name_of(foo)
"foo"

当前回答

import inspect

def my_first_function():
    func_name = inspect.stack()[0][3]
    print(func_name)  # my_first_function

or:

import sys

def my_second_function():
    func_name = sys._getframe().f_code.co_name
    print(func_name)  # my_second_function

其他回答

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

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
my_function.func_name

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

import dis
dis.dis(my_function)

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

如果你对类方法也感兴趣,Python 3.3+除了__name__还有__qualname__。

def my_function():
    pass

class MyClass(object):
    def method(self):
        pass

print(my_function.__name__)         # gives "my_function"
print(MyClass.method.__name__)      # gives "method"

print(my_function.__qualname__)     # gives "my_function"
print(MyClass.method.__qualname__)  # gives "MyClass.method"
import inspect

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

在哪里

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

Try

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

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