How to Use a Dispatch Table in Python (Map Strings to Functions)
Maps string command names to callable functions in a dictionary, then dispatches calls safely with error handling.
Python code
36 linesdef 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:
raise ValueError("Division by zero")
return a / b
dispatch = {
"add": add,
"subtract": subtract,
"multiply": multiply,
"divide": divide,
}
def apply_operation(operation, x, y):
func = dispatch.get(operation)
if func is None:
raise KeyError(f"Unknown operation: {operation}")
return func(x, y)
if __name__ == "__main__":
result = apply_operation("multiply", 6, 7)
print(result)
Output
42
How it works
The dispatch dictionary stores function references as values, keyed by string names. apply_operation looks up the function with dict.get(), which returns None for missing keys instead of raising a KeyError — then the explicit check converts that into a clear error message. Each function is called with the provided arguments, and the result is returned directly. This pattern avoids long chains of if/elif statements when mapping names to behaviors. The raise statements inside functions and the dispatcher give clear feedback for invalid input.
Common mistakes
- Forgetting the `.get()` method and causing an unhelpful `KeyError` for unknown operations
- Storing function calls (with parentheses) instead of function references in the dispatch dict
- Not validating `None` results from `dict.get()` before attempting to call the function
Variations
- Use `functools.partial` to bind extra arguments to each function in the dispatch table
- Use a `match` statement (Python 3.10+) instead of a dict for imperative dispatch logic
Real-world use cases
- A CLI tool that maps subcommand strings to their handler functions (e.g., `add`, `delete`, `status`).
- An HTTP API router that maps endpoint names to view functions in a lightweight web framework.
- An event-processing worker that dispatches named event types to the right handler callback.
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.