Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteiTechGuides 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.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Look 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.
#1 Best Overall
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:
Rank #2
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.
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().
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.
Quick Recap
Best Value
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.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →

