
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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") print(add.__name__)
Output
The output of the above example is as shown below −
The function name is add
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__)
Output
Following is an output of the above code −
some_func
- Related Articles
- How to get a variable name as a string in Python?
- How to get a variable name as a string in PHP?
- Python How to get function name?
- How to execute a JavaScript function when I have its name as a string?
- How to call a function of a module from a string with the function's name in Python?
- How to call a function of a module from a string with the function's name in Python?
- How to pass Python function as a function argument?
- How to get current function name in PHP?
- How to pass a dictionary as argument in Python function?
- How to call a function from its name stored in a string using JavaScript?
- How to get the entire document HTML as a string in JavaScript?
- How to get the length of a string in Python?
- How to get the size of a string in Python?
- How to get integer values from a string in Python?
- How to get a string from a tkinter filedialog in Python 3?
