liveBook · Manning

Dispatch table

As explained in Python Workout, Second Edition

A dispatch table is a mapping from selectable operation identifiers to callable implementations that can be looked up and invoked.

When input selects an operation, map each identifier to a function instead of expanding an if/elif chain. Look up the function, then call it with the required arguments. section 7.7

A calculator can split an expression into an operator and operands, convert the operands, and invoke operations[op](first, second). A dictionary stores functions as values, while **kwargs can build a similar table dynamically for menu options. section 7.7 section 9.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

Use the executable calculator pattern to inspect function registration, input unpacking, conversion, and final lookup-and-call behavior. section 7.7

Practice the pattern by varying the selection and input path:

  • Use split(maxsplit=3) when the final field may contain spaces instead of assuming an exact number of results. section 7.7
  • Display valid menu keys by joining sorted dictionary keys before requesting input. section 9.7

How Python Workout, Second Edition covers it

How deep it goes
Explains hard-coded and dynamic tables, lookup-and-call syntax, input unpacking, and maxsplit, but not broader dispatch architecture.
Examples
Uses an arithmetic calculator and a zero-argument menu whose keyword arguments provide selectable functions.
What it assumes
Assumes familiarity with dictionaries, functions, str.split, argument unpacking, and **kwargs.
What you can do after
Build calculator and menu dispatchers by registering functions, parsing selections, and invoking the selected callable.
How it connects
Connects dictionaries, functions, str.split, argument unpacking, **kwargs, the operator module, and match case.

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, Second Edition. The section links point to the parts of the book it draws on.