To get the name of a function when using Python, you can access the __name__ property.
def function_example():
pass
print(function_example.__name__)
#Output:
function_example
If you are in a function and want to know the name of that function, then you can use the Python inspect module.
import inspect
def function_example():
frame = inspect.currentframe()
return inspect.getframeinfo(frame).function
print(function_example())
#Output:
function_example
When working in Python, the ability to get the names of different objects or functions can be useful.
One such example is if you want to get the name of a function.
To get the name of a function when using Python, you can simply access the __name__ property.
Below is a simple example showing you how to get the name of a function in Python.
def function_example():
pass
print(function_example.__name__)
#Output:
function_example
Get Name of Function when Inside Function in Python
If you want to get the name of a function when you are already in a function, then you have to do a little more work.
To get the name of the function you are currently in, you can use the inspect module.
The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects.
To get the name of the function you are currently in, you can use inspect to get the current frame with currentframe(), and then use the function property.
Below shows you how to get the name of the function you are currently in in Python.
import inspect
def function_example():
frame = inspect.currentframe()
return inspect.getframeinfo(frame).function
print(function_example())
#Output:
function_example
Hopefully this article has been useful for you to be able to learn how to get the name of a function using Python.