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.

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

Python code

36 lines
Python 3.9+
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:
        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

stdout
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

  1. Use `functools.partial` to bind extra arguments to each function in the dispatch table
  2. 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

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.