Get Function Name in Python

Get Function Name in Python

Rayven Esplanada Apr-29, 2021 Jan-31, 2021 Python Python Function

This tutorial will introduce how to get the function name in Python.

Use the __name__ Property to Get the Function Name in Python

In Python, every single function that is declared and imported in your project will have the __name__ property, which you can directly access from the function.

To access the __name__ property, just put in the function name without the parentheses and use the property accessor .__name__. It will then return the function name as a string.

The below example declares two functions, calls them, and prints out their function names.

def functionA():
    print ("First function called!")

def functionB():
    print ("\nSecond function called!")

functionA()
print ("First function name: ", functionA.__name__)

functionB()
print ("Second function name: ", functionB.__name__)

Output:

First function called!
First function name:  functionA
  
Second function called!
Second function name:  functionB

Note that this solution also works with the imported and pre-defined functions. Let’s try it out with the print() function itself and a function from an imported Python module os.

import os

print("Function name: ", print.__name__)
print("Imported function name: ", os.system.__name__)

Output:

Function name:  print
Imported function name:  system

In summary, getting the function name in Python can easily be done by using the function property __name__, a string property containing the function name without the parentheses.

Related Article - Python Function

  • Exit a Function in Python
  • Optional Arguments in Python
  • Fit a Step Function in Python
  • Built-In Identity Function in Python
  • Arguments in the main() Function in Python
  • Python Functools Partial Function