Python | How to get function name ?
Last Updated :
06 Apr, 2023
One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to know certain hacks of functions. This article discusses how to print the name of a function. Let’s discuss certain ways in which this can be done.
Method 1: Get Function Name in Python using function.__name__
This function has been introduced in Python 3 in Python3.
Python3
def GFG():
return "You just called for success !!"
print ( "The name of function is : " + GFG.__name__)
|
Output :
The name of function is : GFG
Method 2: Get Function Name in Python using function.func_name
By using a simple function property function, func_name, one can get the name of the function and hence can be quite handy for the Testing purpose and also for documentation at times. The drawback is that this works just for Python2.
Python
def GFG():
return "You just called for success !!"
print ( "The name of function is : " + GFG.func_name)
|
Output :
The name of function is : GFG
Method 3: Get Function Name in Python using __qualname__ attribute
The __qualname__ gives more complete information than __name__ and therefore can be more helpful in debugging. To extract the name from any object or class, you can also use its __qualname__ attribute.
Python3
def Geekforgeeks():
pass
class Geekforgeeks( object ):
def my_method( self ):
pass
print (Geekforgeeks.__qualname__)
print (Geekforgeeks.my_method.__qualname__)
|
Output :
Geekforgeeks
Geekforgeeks.my_method
Method 4: Get Function Name in Python using the inspect module
This code imports the inspect module and defines a function get_function_name() that returns the name of the function. The function uses the inspect.currentframe() function to get the frame object of the current function, and then returns the co_name attribute of the f_code attribute of the frame object, which is the name of the function.
The inspect.currentframe() function returns a frame object for the frame of the caller. The frame object is an instance of the FrameInfo class, which has several attributes that provide information about the frame, such as the f_code attribute, which is the code object for the function, and the co_name attribute, which is the name of the function.
Finally, the code prints the name of the function using the get_function_name() function.
Python3
import inspect
def get_function_name():
frame = inspect.currentframe()
return frame.f_code.co_name
print ( "The name of function is : " + get_function_name())
|
Output
The name of function is : get_function_name
This approach has a time complexity of O(1) and an auxiliary space of O(1).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...