Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Python does not turn a string into a function automatically. Instead, look up an existing callable by name and call it. For a fixed set of commands, the clearest and safest default is a dictionary that maps accepted strings to function objects. Use getattr() when you need to look up an attribute on a known object or module.

Use a dictionary for a known set of commands

A dispatch dictionary makes the allowed command names explicit and can map them to functions whose Python names differ from the commands users provide. The Python 3.14.8 Programming FAQ recommends this pattern: “The best is to use a dictionary that maps strings to functions.”

def start():
    return "started"

def stop():
    return "stopped"

actions = {
    "go": start,
    "halt": stop,
}

user_command = "go"
try:
    function = actions[user_command]
except KeyError:
    raise ValueError(f"Unknown command: {user_command!r}")

result = function()

The dictionary values are function objects—not strings and not calls. Writing "go": start stores the function for later; writing "go": start() would call it immediately while building the dictionary and store its return value instead. See the Python Programming FAQ for the recommended string-to-function dispatch approach.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Look up a method or module attribute with getattr()

If the name should select an attribute on an object you already have, use getattr(object, name). With no default, a missing attribute raises AttributeError; supplying a default lets you handle a missing name explicitly.

method = getattr(service, method_name, None)
if not callable(method):
    raise ValueError("Unknown method")

result = method()

For names supplied by an external caller, check an allowlist or authorization rule as well as whether the result is callable. getattr() can retrieve any attribute exposed by the object, not just methods intended as commands.

If a programmatically chosen name identifies a module, importing that module is a separate step from looking up its function:

import importlib

module = importlib.import_module("my_package.handlers")
handler = getattr(module, "handle_request")
result = handler()

Only import modules your application expects and trusts; apply the appropriate allowlist to any externally supplied module or function names.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why eval() and exec() are not function lookup tools

eval() evaluates a Python expression, while exec() executes a suite of statements. Both execute code; neither is necessary to call a function already defined in your program. The Python built-in reference warns that eval() on untrusted user-supplied input “will lead to security vulnerabilities,” and gives a corresponding warning for exec(). A restricted __builtins__ mapping does not make either safe for untrusted input.

For ordinary command dispatch, resolve a name only through the dictionary or known object you intend to expose. Consult the official Python built-in functions reference for the behavior and security warnings for eval() and exec().

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When locals() or globals() might fit

locals() and globals() expose namespace mappings, so they can be used for a deliberate name lookup in a scope where the relevant functions are present. They are not general-purpose dispatch registries: which names are available depends on scope, and local-variable behavior has version-specific details. In particular, do not rely on writing to locals() to change local variables in every context; Python’s documentation notes changed locals semantics in Python 3.13. For a known command set, an explicit dictionary is easier to reason about and maintain.

Choose the lookup method by what the string represents

What the string names Use Why
One of a finite set of application commands A dictionary of command names to function objects Clearly limits and documents the accepted commands.
An attribute on a known object, class, or module getattr(), followed by a callable and authorization check where needed Looks up an attribute on the specific object.
A module to load programmatically importlib.import_module(), then attribute lookup Module loading and function lookup are distinct steps.
A Python expression or statement text Not ordinary function lookup; avoid eval() and exec() for untrusted input These execute code rather than safely selecting an existing function.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.