How to get a function name as a string?

后端 未结 12 2345
后悔当初
后悔当初 2020-11-22 04:35

In Python, how do I get a function name as a string, without calling the function?

def my_function():
    pass

print get_function_name_as_string(my_function         


        
12条回答
  •  我在风中等你
    2020-11-22 05:13

    To get the current function's or method's name from inside it, consider:

    import inspect
    
    this_function_name = inspect.currentframe().f_code.co_name
    

    sys._getframe also works instead of inspect.currentframe although the latter avoids accessing a private function.

    To get the calling function's name instead, consider f_back as in inspect.currentframe().f_back.f_code.co_name.


    If also using mypy, it can complain that:

    error: Item "None" of "Optional[FrameType]" has no attribute "f_code"

    To suppress the above error, consider:

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

提交回复
热议问题