Calling a function of a module by using its name (a string)
To call a function from a module by using its name as a string, you can use the importlib
module.
Here's an example:
import importlib
def greet(name):
print(f"Hello, {name}")
def greet_module(module_name, func_name, *args):
# import the module
module = importlib.import_module(module_name)
# get the function from the module
func = getattr(module, func_name)
# call the function
func(*args)
# call the greet function in the greet module
greet_module("greet", "greet", "Alice")
# Output: "Hello, Alice"
Watch a video course
Python - The Practical Guide
You can also use the exec
function to execute a string as Python code. For example:
def greet_module(module_name, func_name, *args):
# import the module
exec(f"import {module_name}")
# call the function
exec(f"{module_name}.{func_name}(*args)")
# call the greet function in the greet module
greet_module("greet", "greet", "Alice")
# Output: "Hello, Alice"
However, using exec
is generally not recommended, as it can be dangerous if you are running untrusted code. It is best to use importlib
when possible.