How to Call Function by String Name in Python?

As an experienced Python developer, I have often needed to dynamically invoke functions based on string names while working on a command-line interface, it is a technique that’s incredibly useful for building flexible and maintainable code. In this tutorial, I will walk you through multiple approaches to dynamically call function by string name in Python with examples.

Call Function by String Name in Python

Let me explain important methods to call function by string name in Python.

Read How to use the Pow() method in Python?

Method 1: Use the globals() Function

The globals() function returns a Python dictionary containing all global variables in your current namespace, including functions. This makes it a simple way to access functions by name.

def say_hello(name):
    return f"Hello, {name}!"

def say_goodbye(name):
    return f"Goodbye, {name}!"

# Get the function by string name
function_name = "say_hello"
function = globals()[function_name]

# Call the function
result = function("John")
print(result) 

Output:

Hello, John!

You can see the output in the below screenshot.

call function by string name python

The globals() approach is simple and effective for accessing functions in the global namespace. However, it only works for functions defined at the global level and doesn’t handle functions in imported modules.

Check out How to Set Global Variables in Python Functions?

Method 2: Use getattr() for Module or Class Functions

The getattr() function is more flexible than globals() because it can access attributes (including functions) of any object, including modules and class instances.

For Module Functions:

import math

# Get a function from the math module
function_name = "sqrt"
function = getattr(math, function_name)

# Call the function
result = function(16)
print(result)

Output:

4.0

You can see the output in the below screenshot.

python call function by string

This method is especially useful when working with module functions, as demonstrated in the above example.

For Class Methods:

class Calculator:
    def add(self, a, b):
        return a + b

    def subtract(self, a, b):
        return a - b

    def multiply(self, a, b):
        return a * b

# Create an instance
calc = Calculator()

# Get a method by string name
method_name = "multiply"
method = getattr(calc, method_name)

# Call the method
result = method(5, 3)
print(result)  # Output: 15

The getattr() function is useful for accessing methods of class instances, making it ideal for object-oriented programming.

Read How to Return Multiple Values from a Function in Python?

Method 3: Use locals() for Local Functions

Similar to globals(), the locals() function returns a dictionary of the current local namespace. This is useful when you want to access functions defined within another function.

def outer_function():
    def inner_function1():
        return "This is inner function 1"

    def inner_function2():
        return "This is inner function 2"

    function_name = "inner_function2"
    function = locals()[function_name]
    return function()

print(outer_function()) 

Output:

This is inner function 2

You can see the output in the below screenshot.

python call function from string

This approach is helpful when dealing with closures or when you want to dynamically call locally defined functions.

Check out How to Access Variables Outside a Function in Python?

Method 4: Use eval()Function

The eval() function evaluates a string as a Python expression. While it can be used to call functions by name, it comes with significant security risks, especially when processing user input.

def add(a, b):
    return a + b

function_name = "add"
result = eval(f"{function_name}(3, 5)")
print(result)  # Output: 8

Use eval() with untrusted input can lead to code injection vulnerabilities. I recommend using one of the other methods instead whenever possible.

Read How to Use Static Variables in Python Functions?

Method 5: Function Dispatch Dictionary

A more explicit and secure approach is to create a dictionary that maps string names to function references:

def function1(x):
    return x * 2

def function2(x):
    return x * x

# Create a dispatch dictionary
function_map = {
    "double": function1,
    "square": function2
}

# Call function by string name
function_name = "square"
if function_name in function_map:
    result = function_map[function_name](4)
    print(result)  # Output: 16
else:
    print("Function not found")

This pattern provides a clean way to call functions by name while maintaining control over which functions can be accessed, making it ideal for command-line interfaces or API endpoint routing.

Check out How to Define a Function in Python?

Comparison of Methods

Here’s a comparison of the different approaches based on pros, cons, and best uses.

MethodProsConsBest Used For
globals()Simple, straightforwardLimited to global scopeSmall scripts, quick solutions
getattr()Works with modules and objectsRequires object referenceOOP, module functions
locals()Accesses local functionsLimited to local scopeFunctions within functions
eval()FlexibleSecurity risks, slowerControlled environments only
Function MapExplicit, secureRequires manual setupCommand interfaces, routing

Handle Edge Cases and Errors

In this example, I will explain how to handle situations where a function name is stored as a string, but the function itself may not exist. It provides two methods to safely attempt calling the function while avoiding errors.

try:
    function_name = "non_existent_function"

    # Method 1: Using getattr with a default
    function = getattr(math, function_name, None)
    if function is not None:
        result = function()
    else:
        print("Function not found")

    # Method 2: Using dictionary get with a default
    function = function_map.get(function_name)
    if function:
        result = function()
    else:
        print("Function not found")

except Exception as e:
    print(f"Error calling function: {e}")

This approach is useful when working with dynamic function calls, such as in plugins, API calls, or command-based systems.

Read How to Get the Name of a Function in Python?

Application: Build a Simple Command-Line Tool

Let’s put all the above concepts together in a practical example—a simple command-line calculator:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "Error: Division by zero"
    return a / b

# Function map
operations = {
    "add": add,
    "subtract": subtract,
    "multiply": multiply,
    "divide": divide
}

def calculate(operation, a, b):
    if operation in operations:
        func = operations[operation]
        return func(a, b)
    else:
        return f"Unknown operation: {operation}"

# Example usage
print(calculate("add", 5, 3))       # Output: 8
print(calculate("multiply", 4, 7))  # Output: 28
print(calculate("power", 2, 3))     # Output: Unknown operation: power

This pattern is commonly used in real-world Python applications that need to route commands or requests to the appropriate handler functions.

Check out How to Use the Input() Function in Python?

Conclusion

In this article, I explained how to call function by string name in Python. I discussed five important methods to achieve this task such as using the globals() function, using getattr() for module or class functions, using locals() for local functions, using the eval() function, and function dispatch.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.