Pass the module object and the function name string to Python’s built-in getattr(module, func_name) function and immediately invoke the returned callable (getattr(math, "sqrt")(16)), validating against an explicit allowlist of permitted function names whenever the string originates from user input, CLI arguments, or configuration files.
Basic Example
import math
func_name = "sqrt"
# 1. Recommended: Retrieve the function attribute dynamically with getattr() and call it
func = getattr(math, func_name)
result = func(25)
print(result)
# Output: 5.0
# 2. Safe lookup with a fallback default and `callable()` guard:
unknown_name = "non_existent"
fn = getattr(math, unknown_name, None)
if callable(fn):
print(fn(25))
else:
print(f"Function {unknown_name!r} not found or not callable")
# Output: Function 'non_existent' not found or not callable
# 3. Security best practice for untrusted / external strings (explicit dispatch allowlist):
ALLOWED_OPS = {
"sqrt": math.sqrt,
"ceil": math.ceil,
"floor": math.floor,
}
user_op = "ceil"
if user_op in ALLOWED_OPS:
print(ALLOWED_OPS[user_op](4.2))
# Output: 5
Key Details & Edge Cases
- Security warning — NEVER pass untrusted strings directly to
getattr(mod, user_input):- Every Python module exposes imported dependencies and dunder attributes in its global namespace (for example,
getattr(my_module, "os")orgetattr(my_module, "__builtins__")). If an external user controlsfunc_name, unrestrictedgetattr()allows arbitrary module traversal or unintended side effects. Always gate external input with an explicitdictallowlist (ALLOWED_FUNCS[name]) or a module__all__check.
- Every Python module exposes imported dependencies and dunder attributes in its global namespace (for example,
- Verify
callable(fn)before invoking:- Modules contain non-callable constants, classes, and submodules alongside functions (for instance,
getattr(math, "pi")returns3.141592653589793, sogetattr(math, "pi")()raisesTypeError: 'float' object is not callable). Checkcallable(fn)whenever the attribute type isn’t guaranteed.
- Modules contain non-callable constants, classes, and submodules alongside functions (for instance,
- Combining dynamic module import with dynamic function lookup (
importlib.import_module):- When both the module path and function name are strings (such as plugin entry points
"pkg.handlers:process_order"), import the module first withimportlib.import_module()and then callgetattr():import importlib mod_path, func_name = "math:factorial".split(":") mod = importlib.import_module(mod_path) result = getattr(mod, func_name)(5) # Output: 120
- When both the module path and function name are strings (such as plugin entry points
- Calling a function defined in the current module (
globals()vs.sys.modules[__name__]):- To dynamically call a top-level function in the currently executing file, pass
sys.modules[__name__]togetattr()(getattr(sys.modules[__name__], "my_helper")(arg)) or look it up inglobals()["my_helper"](arg)—avoidlocals()for dynamic invocation, aslocals()inside functions reflects local variables rather than module-level functions.
- To dynamically call a top-level function in the currently executing file, pass
- Never use
eval(f"{func_name}()"):eval()parses and executes arbitrary Python syntax, creating a critical remote-code-execution (RCE) vulnerability and incurring bytecode compilation overhead on every call.
Comparison of Dynamic Function Invocation Approaches in Python
| Approach | Accepts Untrusted Input Safely? | Works Across External Modules? | Performance | Best Used When |
|---|---|---|---|---|
ALLOWED_FUNCS[name](*args) (Recommended for external input) |
Yes (strict allowlist) | Yes (explicitly registered callables) | $O(1)$ dict lookup | CLI subcommands, API/RPC routers, webhook handlers, and user-configurable plugins. |
getattr(mod, name)(*args) (Recommended for internal reflection) |
No (can access any module attribute/import) | Yes (any imported module object) | $O(1)$ attribute lookup | Internal frameworks, test runners, serializers, and trusted metadata-driven dispatch. |
getattr(importlib.import_module(mod_name), func_name) |
No (unless module & function are allowlisted) | Yes (loads module by string path too) | Import cached in sys.modules |
Dynamic plugin systems loading "package.module:callable" strings at runtime. |
eval(f"{name}()") (Avoid) |
No (severe RCE security vulnerability) | Only if already imported in scope | Slow (compiles AST on every call) | Never use for dynamic function dispatch. |
You must log in or register to comment.
