liveBook · Manning

Dispatch table

As explained in Python Workout: 50 ten-minute exercises

A dispatch table is a mapping from keys representing operations or cases to callable implementations selected at runtime.

When a command string contains an operator such as + or **, a dispatch table maps that key to the function that should handle it. A dictionary stores the functions as values, so retrieving operations[op] produces a callable that can immediately receive the parsed operands. section 6.7

A practical dispatch-table workflow is:

  • Define one function for each operation. section 6.7
  • Map input keys such as +, -, or ** to those functions. section 6.7
  • Split the input, unpack its parts, convert operands, and invoke the selected function. section 6.7
  • Use maxsplit when the input may contain additional separators after the expected fields. section 6.7

Dynamic menu dispatch

A menu can accept keyword arguments whose names become menu options and whose zero-argument functions become handlers. The resulting dictionary is created dynamically with **kwargs; its keys can be sorted and joined to display valid choices. section 8.7

def add(a,b):
    return a + b
 
def sub(a,b):
    return a - b
 
def mul(a,b):
    return a * b
 
def div(a,b):
    return a / b

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

def mod(a,b):
    return a % b
 
def calc(to_solve):
    operations = {'+' : add,                    #1
                  '-' : sub,
                  '*' : mul,
                  '/' : div,
                  '**' : pow,
                  '%' : mod}
 
    op, first_s, second_s = to_solve.split()    #2
    first = int(first_s)                        #3
    second = int(second_s)
 
    return operations[op](first, second)        #4

Complete prefix-calculator implementation showing operation registration, input unpacking, integer conversion, and callable lookup. section 6.7

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains dictionary-based lookup, input parsing, invocation, maxsplit, and dynamic **kwargs construction, but not deeper dispatch internals.
Examples
Uses a prefix calculator with arithmetic operators and a dynamically assembled zero-argument menu.
What it assumes
Assumes familiarity with functions and dictionaries while reinforcing string splitting, unpacking, and keyword-argument dictionaries.
What you can do after
Build it from scratch using Python dictionaries to register callable handlers and route parsed input to them.
How it connects
Connects dictionaries, functions, string splitting, unpacking, keyword arguments, and conditional module execution.

Also explained in

Compare how 2 books explain dispatch table →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.