To call a function from a module using its name as a string in Python, you can use a combination of getattr()
(to dynamically fetch the function) and importlib
(to import the module by name if needed). Here’s how to do it:
1. If the Module is Already Imported
Use getattr()
on the imported module object:
import math # Example module
function_name = "sqrt" # Name of the function as a string
func = getattr(math, function_name) # Get the function reference
result = func(25) # Call the function
print(result) # Output: 5.0
2. If the Module Name is Also a String
Use importlib.import_module()
to dynamically import the module:
import importlib
module_name = "math" # Name of the module as a string
function_name = "sqrt"
# Import the module dynamically
module = importlib.import_module(module_name)
# Get the function and call it
func = getattr(module, function_name)
result = func(25)
print(result) # Output: 5.0
3. For Functions in the Current Module
Use globals()
to access the current module’s functions:
def greet():
return "Hello, World!"
function_name = "greet"
func = globals()[function_name] # Get the function from the global scope
print(func()) # Output: Hello, World!
4. Handling Optional Parameters and Arguments
Pass arguments dynamically using *args
and **kwargs
:
import math
function_name = "pow"
func = getattr(math, function_name)
# Call pow(2, 3) = 8
result = func(2, 3)
print(result) # Output: 8.0
5. Error Handling
Check if the function exists before calling it:
module = importlib.import_module("math")
function_name = "invalid_function"
if hasattr(module, function_name):
func = getattr(module, function_name)
func()
else:
print(f"Function '{function_name}' not found in module.")
6. Security Considerations
Avoid using this approach with untrusted input (e.g., user-provided strings), as it can lead to code execution vulnerabilities. If security is a concern, use a predefined allowlist of allowed functions:
# Safe allowlist approach
ALLOWED_FUNCTIONS = {"sqrt", "log", "sin"}
function_name = "sqrt" # User-provided input
if function_name in ALLOWED_FUNCTIONS:
func = getattr(math, function_name)
result = func(25)
else:
print("Function not allowed.")
Full Example
import importlib
def call_function(module_name, function_name, *args, **kwargs):
try:
module = importlib.import_module(module_name)
func = getattr(module, function_name)
return func(*args, **kwargs)
except ImportError:
print(f"Module '{module_name}' not found.")
except AttributeError:
print(f"Function '{function_name}' not found in module '{module_name}'.")
# Example usage
result = call_function("math", "sqrt", 25)
print(result) # Output: 5.0
Key Notes
getattr()
: Fetches attributes (like functions) from objects (modules, classes, etc.).importlib.import_module()
: Safely imports modules by name (as a string).- Security: Never use this with untrusted input unless properly validated.
- Error Handling: Always handle
ImportError
(invalid module) andAttributeError
(invalid function).