How do you dynamically call a module function using its name as a string in Python? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you dynamically call a module function using its name as a string in Python?

message-square
0

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") or getattr(my_module, "__builtins__")). If an external user controls func_name, unrestricted getattr() allows arbitrary module traversal or unintended side effects. Always gate external input with an explicit dict allowlist (ALLOWED_FUNCS[name]) or a module __all__ check.
  • Verify callable(fn) before invoking:
    • Modules contain non-callable constants, classes, and submodules alongside functions (for instance, getattr(math, "pi") returns 3.141592653589793, so getattr(math, "pi")() raises TypeError: 'float' object is not callable). Check callable(fn) whenever the attribute type isn’t guaranteed.
  • 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 with importlib.import_module() and then call getattr():
      import importlib
      
      mod_path, func_name = "math:factorial".split(":")
      mod = importlib.import_module(mod_path)
      result = getattr(mod, func_name)(5)  # Output: 120
      
  • 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__] to getattr() (getattr(sys.modules[__name__], "my_helper")(arg)) or look it up in globals()["my_helper"](arg)—avoid locals() for dynamic invocation, as locals() inside functions reflects local variables rather than module-level functions.
  • 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.