HOWTO · Python

How to Call a Function From String Name in Python

It demonstrates how to call a function from a string in Python

On this page

When a function name arrives as a string, look it up in a deliberate set of allowed functions and call the resulting function object. A dictionary is usually the clearest choice for commands or other user-selected actions: it makes the available names visible and keeps arbitrary input from selecting unrelated code.

Use a dictionary to map approved names to functions

Define the functions normally, then map the accepted strings to those function objects. Look up the requested name and check that the result is callable before invoking it. This example handles an unknown name without attempting a call:

The supplied runtime run completed this self-contained example with exit code 0 and printed 8. Run it with:

def add(left, right):
    return left + right


def multiply(left, right):
    return left * right


functions = {"add": add, "multiply": multiply}
name = "add"
function = functions.get(name)

if callable(function):
    print(function(5, 3))
else:
    print(f"Unknown function: {name}")
8

The mapping is an allowlist: only names you add to functions can be selected. Use .get() when a missing name is an expected input, and decide how the application should report or handle an unknown name. If the functions take different arguments, validate the arguments for the selected operation as well; successful name lookup does not guarantee that the call signature is correct.

Use getattr() to retrieve an attribute from an object or module

Use getattr(object, name, default) when the string should select an attribute on a particular object or module. The third argument supplies a value when that attribute is absent. Then check that the value is callable: an existing attribute may be data rather than a function.

The supplied runtime run completed this example with exit code 0 and printed 8. It retrieves a bound instance method: Python binds calculator to the method, so pass only the method’s remaining arguments. Run it with:

class Calculator:
    def add(self, left, right):
        return left + right


calculator = Calculator()
name = "add"
operation = getattr(calculator, name, None)

if callable(operation):
    print(operation(5, 3))
else:
    print(f"No callable attribute named {name}")
8

The same pattern works with a module object, for example getattr(math, name, None) after importing math. Looking up an instance method on the instance returns a bound method; looking it up on the class returns the unbound function and requires the instance as an argument. Restrict the source object and allowed attribute names when the string comes from outside your code.

Use globals() and locals() only when the namespace is intentional

globals() returns the current module’s global namespace. It does not return local variables. A global lookup can be useful when functions intentionally live in that module. The supplied runtime run completed this example with exit code 0 and printed 8. Run it with:

def add(left, right):
    return left + right


name = "add"
function = globals().get(name)

if callable(function):
    print(function(5, 3))
else:
    print(f"Unknown global function: {name}")
8

locals() refers to the local namespace at the point where it is called. Inside a function, it can expose names local to that function; it does not inspect the caller’s locals or provide a general search through the program. Its behavior is tied to scope, so it is usually less clear and less suitable as a dispatcher than an explicit mapping. For background on dictionaries, see the Python dictionary tutorial.

Why eval() is risky for function lookup

eval() evaluates a Python expression, rather than looking up only one approved function name. For example, eval("add(5, 3)") parses and evaluates a call expression using the names available in its evaluation environment. If an expression contains untrusted input, evaluating it can run code with the privileges of the Python process. Do not use eval() to dispatch names supplied by users, files, network requests, or other untrusted sources.

If an expression truly comes from a trusted, controlled source, Python documents the behavior and namespace parameters of eval(). For ordinary function selection, a dictionary allowlist is simpler and limits what the input can choose. Parsing or validating text does not make arbitrary evaluation a safe substitute for an explicit set of operations.

Choose the lookup method that fits your input

Use a dictionary when the available actions should be explicit, especially for user-provided or external names. Use getattr() when the object or module is already chosen and the string is meant to select one of its attributes; check the default and callability, and account for method binding. Use globals() only when module-level lookup is intentional. Use locals() only when code deliberately needs names in its current local scope, not as a general dispatcher. Avoid eval() for name lookup when the input is not fully trusted.

In each case, lookup and invocation are separate decisions: first constrain which callable may be selected, then pass arguments that match its interface. For a fixed set of commands, that separation makes the behavior easier to audit and maintain.