Call a Function Dynamically by Name in Python

Use globals() to look up and call a function by its name as a string, with optional arguments.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 13 views 0 copies

Python code

25 lines
Python 3.9+
def greet():
    return "Hello from greet!"

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

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

if __name__ == "__main__":
    func_name = "add"
    args = (3, 5)
    
    # Call function dynamically by name from globals
    result = globals()[func_name](*args)
    print(f"{func_name}({', '.join(map(str, args))}) = {result}")
    
    func_name = "multiply"
    args = (4, 6)
    result = globals()[func_name](*args)
    print(f"{func_name}({', '.join(map(str, args))}) = {result}")
    
    func_name = "greet"
    result = globals()[func_name]()
    print(f"{func_name}() = {result}")

Output

stdout
add(3, 5) = 8
multiply(4, 6) = 24
greet() = Hello from greet!

How it works

The globals() function returns a dictionary representing the current global symbol table, mapping names to their values. Accessing globals()[func_name] retrieves the function object associated with the string name. The * unpacking operator passes each element of the tuple args as a separate argument to the function. This approach works for any callable defined at the module level, including imported functions passed through globals().

Common mistakes

  • Forgetting to use the `*` operator when passing a tuple of arguments.
  • Assuming the function name exists, which raises a `KeyError` if not.
  • Trying to call methods or nested functions that are not in the global scope.

Variations

  1. Use `locals()` instead of `globals()` when the function is defined inside another function.
  2. Use `getattr(module, func_name)` to call a function imported from a module.

Real-world use cases

  • Dispatching HTTP handlers based on a route string without writing a long if‑else chain.
  • Building a plugin system where plugin names are read from a config file and invoked at runtime.
  • Implementing a calculator CLI that maps operator symbols to function names entered by the user.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.