Link String to Function in Python: How-To

Formulas & functions · Updated November 22, 2026

Yes, you can link a string to a function in Python, and the most direct way is to use a dictionary that maps string keys to function objects. For example, if you have functions named add, subtract, and multiply, you can create a dict like ops = {'add': add, 'subtract': subtract, 'multiply': multiply} and then call ops['add'](2, 3) to invoke the add function. This approach is safe, explicit, and works in any Python version.

Why Use a Dictionary Instead of eval()

The most common mistake beginners make is reaching for eval() or exec() to turn a string into executable code. For instance, eval('add(2, 3)') would work, but it is a severe security risk if the string comes from user input—it can execute arbitrary code. A dictionary lookup only calls the specific function you have mapped, so it is both safer and more predictable. It also makes your code easier to read and debug because the mapping is explicit.

How to Map Strings to Functions

Here is a step-by-step breakdown of the dictionary method:

  • Define your functions normally (e.g., def add(a, b): return a + b).
  • Create a dictionary where keys are the strings you want to use (e.g., 'add') and values are the function objects (just the name, no parentheses).
  • Access the function using the string key and call it with parentheses: result = ops['add'](5, 3).

This pattern is extremely common in command-line tools, menu systems, and API routers. For example, a simple calculator could map operator symbols to functions:

def add(a, b): return a + b
def sub(a, b): return a - b
ops = {'+': add, '-': sub}
print(ops['+'](10, 4))  # Output: 14

Using getattr() for Class Methods

If your functions are methods of a class, you can use getattr() to retrieve them by name. For instance, getattr(obj, 'method_name') returns the bound method, which you can then call. This is useful when you have a string that matches a method name exactly:

class Greeter:
    def hello(self):
        return "Hello!"
    def goodbye(self):
        return "Goodbye!"

g = Greeter()
action = 'hello'
result = getattr(g, action)()  # Calls g.hello()
print(result)  # Output: Hello!

Be careful: getattr will raise an AttributeError if the method does not exist, so you may want to provide a default or check with hasattr() first.

Handling Unknown Strings Gracefully

In real applications, you cannot guarantee that every string maps to a function. You should handle the case where the key is missing. Using a dictionary, you can use the .get() method to provide a fallback, or check with if key in ops:. For example:

def default_func(*args):
    return "Unknown operation"

ops = {'add': add, 'sub': sub}
result = ops.get('multiply', default_func)(2, 3)
print(result)  # Output: Unknown operation

Alternatively, you can wrap the call in a try/except KeyError to handle missing keys.

When to Use a Dispatch Table vs. if-elif Chains

If you have only two or three possible strings, a simple if/elif chain is perfectly readable. But as the number of options grows, a dictionary (often called a dispatch table) scales better. It separates the mapping from the logic, making it easier to add new functions without modifying the control flow. For example, a command-line parser with dozens of commands benefits greatly from a dictionary. The dictionary also allows you to iterate over all available commands, which is handy for generating help text.

Common Pitfalls and Misconceptions

One misconception is that you need to use globals() or locals() to look up functions by name. While globals()['add'] works, it is essentially a dictionary lookup on the global namespace, but it is less explicit and can be fragile if the function name changes. Another pitfall is forgetting that functions are first-class objects—you must pass the function reference without parentheses. A common error is writing ops = {'add': add()} which would call the function immediately and store the result, not the function itself.

Also, be aware that if you are using a dictionary to map strings to functions that take different numbers of arguments, you need to handle that carefully. The dictionary itself does not enforce signatures; you must ensure that the calling code passes the correct arguments for each function. This is often fine if all functions share a similar signature, but if not, you may need to use *args and **kwargs or store metadata alongside the function.

Frequently Asked Questions

Can I use a string to call a function without a dictionary?

Yes, you can use eval() or globals(), but both have drawbacks. eval() is a security risk and considered bad practice. globals()['func_name']() works but is less readable and ties you to the global scope. The dictionary method is the recommended approach because it is explicit, safe, and flexible.

How do I link a string to a function with arguments?

You map the string to the function object, and when you call it, you pass the arguments. For example, ops['add'](3, 5) calls the add function with 3 and 5. If the function takes keyword arguments, you can pass them as ops['func'](x=1, y=2).

What if the function is in another module?

You can import the module and use getattr(module, 'func_name') to get the function. For instance, import math then getattr(math, 'sqrt')(16) returns 4.0. Alternatively, you can build the dictionary from the module’s functions explicitly.

Is there a way to link a string to a lambda function?

Yes, lambdas are functions too, so you can store them in a dictionary. For example, ops = {'double': lambda x: x*2} and then call ops['double'](5) returns 10. This is useful for short, one-off operations.

Does this work in Python 2 and Python 3?

Yes, the dictionary mapping technique works in all Python versions. However, in Python 2, you should use print as a statement, but the function mapping itself is identical. The examples above are written for Python 3, but the principle is the same.

Alternatives for Advanced Scenarios

If you need to link strings to functions based on patterns (like regular expressions), you might use a list of tuples or a more complex dispatch mechanism. For instance, a simple router could iterate over patterns and call the first matching function. This is common in web frameworks like Flask or Django, where URLs are mapped to view functions. In those cases, the framework provides decorators like @app.route('/path') that internally build a mapping from URL strings to functions. You can mimic that pattern with your own decorator if you need similar functionality in a standalone script.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.