
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Function Name as String in Python
In Python, Functions are the first-class object, which means they can be passed around and manipulated like other data types (like integers, strings). This allows to inspect and retrieve the attribute of functions, including their names.
In this article we are going to learn about getting the function names as string, To achieve we are going to use the built-in __name__ attribute. Let's dive into the article to learn more about it.
Using Python Class __name__ Attribute
The Python __name__ attribute is a special built-in variable that helps to determine the context in a which a Python script is being executed. It holds the name of the current module, or the string "__main__" if the script is being run directly.
Example 1
In the following example, We are going to get the name of the defined function using the __name__ attribute.
def tp(): print("WELCOME") x = tp.__name__ print("Result :", x)
Output
Output of the above program is as follows -
Result : tp
Example 2
Consider the following example, where we are going to check if an object is a function and retrieve its name.
def demo(x, y): return x + y if type(demo).__name__ == 'function': print("Result :", demo.__name__)
Output
Output of the above program is as follows -
Result : demo
Example 3
Let's look at the following example, Where we are going to store multiple functions in a list and printing their names.
def demo(): pass def demo1(): pass x = [demo, demo1] for a in x: print("Result :", a.__name__)
Output
Following is the output of the above program -
Result : demo Result : demo1