Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get a function name as a string in Python?
In Python, functions are first-class objects, which means they can be passed around and manipulated like other data types (integers, strings, etc.). This allows us to inspect and retrieve function attributes, including their names as strings.
To get a function name as a string, we use the built-in __name__ attribute that every function object possesses.
The __name__ Attribute
The __name__ attribute is a special built-in variable that stores the name of a function, class, or module as a string. For functions, it contains the original name used when defining the function.
Basic Usage
Here's how to get a function name as a string using the __name__ attribute ?
def greet_user():
print("Hello, welcome!")
# Get function name as string
function_name = greet_user.__name__
print("Function name:", function_name)
Function name: greet_user
Checking Function Type and Name
You can verify if an object is a function and then retrieve its name ?
def calculate_sum(x, y):
return x + y
# Check if object is a function
if callable(calculate_sum) and hasattr(calculate_sum, '__name__'):
print("Function name:", calculate_sum.__name__)
print("Function type:", type(calculate_sum).__name__)
Function name: calculate_sum Function type: function
Working with Multiple Functions
When dealing with multiple functions, you can store them in a list and iterate through their names ?
def add(a, b):
return a + b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
# Store functions in a list
math_functions = [add, multiply, divide]
# Print all function names
for func in math_functions:
print("Function name:", func.__name__)
Function name: add Function name: multiply Function name: divide
Practical Use Cases
Getting function names as strings is useful for debugging, logging, or dynamic function calls ?
def process_data():
return "Data processed"
def validate_input():
return "Input validated"
# Create a function registry
function_registry = {
process_data.__name__: process_data,
validate_input.__name__: validate_input
}
# Call function by name
func_name = "process_data"
if func_name in function_registry:
result = function_registry[func_name]()
print(f"Called {func_name}:", result)
Called process_data: Data processed
Conclusion
The __name__ attribute provides a simple way to get any function's name as a string. This is particularly useful for debugging, logging, dynamic function calls, and creating function registries in Python applications.
