W3docs

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.

Call a function from a module by using its name as a string in Python using the importlib module

import importlib
import math

def call_function(module_name, func_name, *args):
    try:
        module = importlib.import_module(module_name)
        func = getattr(module, func_name)
        return func(*args)
    except (ModuleNotFoundError, AttributeError) as e:
        print(f"Error: {e}")

# call the sqrt function in the math module
result = call_function("math", "sqrt", 16)
print(result)  # Output: 4.0

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

Call a function from a module by using its name as a string in Python using the exec function

def call_function_exec(module_name, func_name, *args, **kwargs):
    args_str = ", ".join(repr(a) for a in args)
    kwargs_str = ", ".join(f"{k}={repr(v)}" for k, v in kwargs.items())
    call_str = f"import {module_name}\nresult = {module_name}.{func_name}({args_str}{', ' + kwargs_str if kwargs_str else ''})"
    exec(call_str, globals(), locals())
    print(locals().get('result'))

# call the sqrt function in the math module
call_function_exec("math", "sqrt", 16)  # Output: 4.0

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.

For production-ready code, always wrap dynamic imports and attribute lookups in try/except blocks to handle ModuleNotFoundError or AttributeError gracefully.