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 call a function of a module from a string with the function\'s name in Python?
In Python, you can dynamically call a function from a module by using its name as a string. This is useful in scenarios where function names are not known until runtime or when building flexible, configurable applications.
Using getattr() Function
The getattr() function retrieves an attribute from an object using a string representing the attribute's name. This is the most common approach for calling functions dynamically from modules.
Example
Here's how to call a function from a module using its string name −
import math
# The function name as a string
function_name = 'sqrt'
# Get the function using getattr
method_to_call = getattr(math, function_name)
# Call the function
result = method_to_call(16)
print(f"Result: {result}")
Result: 4.0
You can also handle cases where the function might not exist −
import math
function_name = 'nonexistent_function'
# Provide a default value if function doesn't exist
method_to_call = getattr(math, function_name, None)
if method_to_call:
result = method_to_call()
print(result)
else:
print(f"Function '{function_name}' not found")
Function 'nonexistent_function' not found
Using globals() Function
The globals() function returns a dictionary of the current global symbol table, allowing you to access functions defined in the current module.
Example
Call a function from the global namespace using its string name −
def greet_user(name):
return f"Hello, {name}!"
def calculate_area(radius):
return 3.14159 * radius * radius
# The function name as a string
function_name = 'greet_user'
# Call the function using globals()
result = globals()[function_name]("Alice")
print(result)
# Call another function
function_name = 'calculate_area'
area = globals()[function_name](5)
print(f"Area: {area}")
Hello, Alice! Area: 78.53975
Using locals() Function
The locals() function returns a dictionary of the current local symbol table, useful for accessing functions within the current scope.
Example
Access and call a local function using locals() −
def main_function():
def helper_function():
return "Helper function called!"
def another_helper(x, y):
return x + y
# The function name as a string
function_name = 'helper_function'
# Call the function using locals()
result = locals()[function_name]()
print(result)
# Call another local function with parameters
math_result = locals()['another_helper'](10, 20)
print(f"Sum: {math_result}")
main_function()
Helper function called! Sum: 30
Using importlib Module
The importlib module provides programmatic importing capabilities, useful for loading modules dynamically at runtime.
Example
Import a module dynamically and call its function −
import importlib
# Import math module dynamically
module_name = 'math'
function_name = 'ceil'
# Import the module dynamically
math_module = importlib.import_module(module_name)
# Call the function using getattr
result = getattr(math_module, function_name)(4.3)
print(f"Ceiling of 4.3: {result}")
# Import another module
random_module = importlib.import_module('random')
random_func = getattr(random_module, 'randint')
random_num = random_func(1, 100)
print(f"Random number: {random_num}")
Ceiling of 4.3: 5 Random number: 42
Comparison of Methods
| Method | Use Case | Scope | Error Handling |
|---|---|---|---|
getattr() |
Module/object functions | Specific module | Can provide defaults |
globals() |
Global functions | Current module | KeyError if not found |
locals() |
Local functions | Current function scope | KeyError if not found |
importlib |
Dynamic module loading | Any module | ImportError for modules |
Conclusion
Use getattr() for calling functions from imported modules, globals() for functions in the current module, and importlib for dynamic module loading. Each method serves specific use cases in dynamic function calling scenarios.
