Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk2 min

How to Call a Python Function Named by a String

A Python string is not a callable. Map approved command strings to function objects, or use getattr for an attribute on a known object; avoid dynamic code execution for lookup.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A string does not become a function in Python: look up the function object the string names, then call it. For a fixed set of commands, use a dictionary that maps approved strings to functions—the Python FAQ calls this the best approach. Use getattr when resolving an attribute on a known object or module, and do not use eval or exec to dispatch untrusted input.

Use a dictionary for a fixed set of commands

A dispatch dictionary is an explicit allowlist: each accepted command points to the function that should handle it. The string can be a simple external command such as "go", even if the implementation function is named start. This is the approach recommended by the Python Software Foundation’s Programming FAQ.

As an Amazon Associate I earn from qualifying purchases.

def start():
    return "started"

def stop():
    return "stopped"

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

user_command = "go"
result = actions[user_command]()

The dictionary stores function objects, not function-name strings. Indexing it resolves the command to a callable; the final parentheses invoke that callable. If input may contain an unsupported command, handle the missing key explicitly:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
def add_user():
    ...

def delete_user():
    ...

commands = {"add": add_user, "delete": delete_user}

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

result = function()

Use getattr for an attribute on a known object

If the requested function is a method or attribute of an object, class, or module you already have, getattr can resolve it by name. Supplying a default, such as None, avoids an AttributeError when the attribute is absent. Check that the result is callable before invoking it:

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

result = method()

When a name comes from an external caller, checking that it is callable is not authorization: an object may expose callable attributes that the caller should not be allowed to invoke. Restrict permitted names with an allowlist or use a dispatch dictionary whose entries represent the approved operations.

Import a module separately when its name is dynamic

If a string identifies a module, load that module with importlib.import_module, then resolve the function attribute. Importing a module and looking up a function on it are separate steps:

import importlib

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

Only import modules your application expects and trusts. If module or function names are provided externally, validate them against an allowlist appropriate to the application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why not use locals(), globals(), eval(), or exec()?

locals() and globals() are scope lookups

These functions expose namespaces, but they are not general-purpose dispatch registries. Which names are present depends on scope, and the behavior of local namespaces has version-specific details; Python’s documentation notes changed locals() semantics in Python 3.13. When the accepted command set is known, a dedicated dictionary makes the permitted operations clearer and avoids relying on incidental names in a scope.

eval() and exec() execute code

eval evaluates a Python expression; exec executes a suite of statements. Neither is needed to look up a function that already exists. The Python 3.14.8 built-in functions reference warns that calling eval with untrusted user-supplied input leads to security vulnerabilities, and gives a corresponding warning for exec. Restricting __builtins__ is not a security mechanism.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.