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.
Python code
25 linesdef 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
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
- Use `locals()` instead of `globals()` when the function is defined inside another function.
- 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
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.