How to Get a Function Name as a String
Method 1: Using the name attribute:
The name attribute is a built-in attribute of functions in Python that returns the name of the function as a string. This is the most straightforward and reliable way to get the name of a function as a string.
def foo(): pass print(foo.__name__) # Output: "foo"
Method 2: Using the inspect module:
The inspect module is a built-in Python module that provides a variety of functions for inspecting live objects, including functions. The getframeinfo() function returns information about a frame object, which represents a stack frame in Python. The currentframe() function returns the frame object for the caller's stack frame. By calling these functions and accessing the function attribute of the returned frame object, we can get the name of the calling function as a string.
import inspect def bar(): pass print(inspect.getframeinfo(inspect.currentframe()).function) # Output: "bar"
Method 3: Using the sys module:
The sys module is a built-in Python module that provides access to various variables and functions used or maintained by the interpreter, including the current stack frame. The _getframe() function returns a frame object representing the stack frame at a given depth in the call stack. By passing in a value of 1 for the depth, we can get the frame object for the caller's stack frame. From there, we can access the co_name attribute of the f_code attribute of the frame object to get the name of the calling function as a string.
import sys def baz(): caller = sys._getframe(1) print(caller.f_code.co_name) # Output: "baz"
Keep in mind that these methods may not work in all cases, especially if the function name is modified or the function is defined in a way that does not follow the usual conventions