How to get a function name as a string in Python?

In this article, we are going to find out how to get a function name as a string in Python.

The first approach is by using the function property __name__. This property will return the name of the function when the property is called. This is only present in Python 3.x version.

Python does not have a main() function, so when the command to run a Python program is given to the interpreter, the level 0 indented code will be executed. Before that, though, it will define a few unique variables. One such unique variable is __name__. The interpreter sets the __name__ variable to "__main__" if the source file is run as the main program. __name__ will be set to the name of the module if this file is being imported from another module.

For Python 2.x, we will use the function property func_name.

Example 1

In the example given below, we are defining a function and we are finding out the name of the function using the function property __name__

def add(a,b):
   res = a + b
   return res
print("The function name is")


The output of the above example is as shown below −

The function name is

Example 2

Following is another example to find out the name of the function using __name__ property −

def some_func():
   return 0
print (some_func.__name__)


Following is an output of the above code −