Python How to get function name?

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to learn how to get the function name in Python. Getting the name any function is a straightforward thing. We have two different ways for Python2 and Python3. Let's see both of them.

Python2

Every function in Python2 has a property called func_name that gives you the name of the current function. Let's see an example. Make sure you are using Python2 while executing the following example.

Example

 Live Demo

# defining a function
def testing_function():
   """
      This is a simple function for testing
   """
return None
print("Function name is (Python2) '{}'".format(testing_function.func_name))

Output

If you execute the above program, then you will get the following result.

Function name is (Python2)'testing_function'

Python3¶

The function property func_name is deprecated in Python3. We will get the name of the using property __name__ of the function. Let's see an example. Make sure you are using Python3 while running the following code.

Example

 Live Demo

# defining a function
def testing_function():
   """
      This is a simple function for testing
   """
return None
print(f"Function name is (Python3) '{testing_function.__name__}'")

Output

If you execute the above program, then you will get the following result.

Function name is (Python3) 'testing_function'

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

raja
Published on 07-Jul-2020 08:42:26
Advertisements