Sitemap
Better Programming

Advice for programmers.

Member-only story

Dispatch Tables in Python

4 min readDec 24, 2018

--

Press enter or click to view image in full size
Photo by Chris Ried on Unsplash

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:

--

--

Andrea Colangelo
Andrea Colangelo

Written by Andrea Colangelo

Technical Lead @ Rapsodoo Italia. Also: Software Engineer, Debian Developer, Ubuntu Developer, Foodie, Jazz lover, Rugby passionate, European