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
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