Python中获取当前函数名的三种方法

  1. 使用__name__获取当前函数名

函数内和函数外都可以用__name__特殊属性。

def get_fun_name_1():
    fun_name = get_fun_name_1.__name__
    print(fun_name)

get_fun_name_1.__name__

输出:get_fun_name_1

  1. 使用sys模块获取当前运行的函数名

sys._getframe()可以用来获取当前函数的句柄,返回FrameType对象

class FrameType:
    @property
    def f_back(self) -> FrameType | None: ...  
    @property
    def f_builtins(self) -> dict[str, Any]: ...
    @property
    def f_code(self) -> CodeType: ...
    @property
    def f_globals(self) -> dict[str, Any]: ...
    @property
    def f_lasti(self) -> int: ...
    # see discussion in #6769: f_lineno *can* sometimes be None,
    # but you should probably file a bug report with CPython if you encounter it being None in the wild.
    # An `int | None` annotation here causes too many false-positive errors.
    @property
    def f_lineno(self) -> int | Any: ...
    @property
    def f_locals(self) -> dict[str, Any]: ...
    f_trace: Callable[[FrameType, str, Any], Any] | None
    f_trace_lines: bool
    f_trace_opcodes: bool
    
----------------------------------------------------------------
sys._getframe().f_code.co_filename  #当前文件名,可以通过__file__获得
sys._getframe(0).f_code.co_name  #当前函数名
sys._getframe(1).f_code.co_name #调用该函数的函数的名字,如果没有被调用,则返回<module>,貌似call stack的栈低
sys._getframe().f_lineno #当前行号

使用下面的代码获取函数的名称

def get_fun_name_2():
    import sys
    fun_name = sys._getframe().f_code.co_name
    print(fun_name)

输出:get_fun_name_2

  1. 使用inspect模块获取当前运行的函数名

inspect模块:https://docs.python.org/zh-cn/3.10/library/inspect.html#retrieving-source-code

def get_fun_name_3():
    import inspect
    fun_name = inspect.currentframe().f_code.co_name
    print(fun_name)

输出:get_fun_name_3
:::info
PS:inspect模块其实就是调用了sys._getframe()来获取的函数运行信息image.png
:::

作者:锡城筱凯

物联沃分享整理
物联沃-IOTWORD物联网 » Python中获取当前函数名的三种方法

发表回复