Member-only story
Dispatch Tables in Python
How to use a quick dictionary lookup to run a function dynamically, instead of a slow, long, boring if-elif statement
Have you ever needed to run different functions according to the value of a variable? The first approach that comes to mind is probably a long series of if-elif statements resembling a C-style switch case.
Well, there is a better option: a dispatch table.
A dispatch table in Python is basically a dictionary of functions. This concept is not Python-specific. In fact, it is quite common in computer science:
“A dispatch table is a table of pointers to functions or methods.” (cit.: Wikipedia)
Dispatch tables are among the most common approaches in OOP to implement late binding. Late binding means looking up by name the function you want to be called at runtime, rather than hardcoding it.
Let’s see what it means to use dispatch tables, how and why you should take advantage of them, and what an example might look like.
The if-elif Approach
Let’s suppose you have a Date object and you need to execute a specific function based on its weekday. This is one way you might make use of a set of if-elif statements:






