Dispatch tables are a useful way to use a string to determine which function to call. Why would you do this? When designing an interface to be used in other people’s code, you can make a single routing function or method public to users, and then use a parameter to determine which “worker” function to pass in.

A really basic no-guardrails example could look like this:

DISPATCH_TABLE = {
    "one": _private_fxn_one,
    "two": _private_fxn_two
}

def public_function(which_function: str):
    result = DISPATCH_TABLE[which_function]()
    return result

def _private_fxn_one():
    return "one"

def _private_fxn_two():
    return "two"

Caveats#

  • Don’t put parentheses on the function in the dispatch table because the function will be called then. This applies generally when using a function as an object,
  • If the private functions have different parameters, you can use kwargs to pass in a standard set of arguments and ignore the unused ones, or generate the parameters based on an argument to the public function.

Sources#

LLM Knowledge Management Agent