Dispatching Behavior by Argument Type with functools.singledispatch
Table of Contents
#
Dispatching Behavior by Argument Type with functools.singledispatch
In a data preprocessing pipeline, samples often come in different types, such as text, images, and tabular rows. Each type needs its own preprocessing and validation logic. A common approach is to put the methods inside each class or to write isinstance checks in the pipeline, but both get messy as the number of behaviors grows.
functools.singledispatch offers another option: it picks which version of a function to run based on the type of the first argument, so the behavior lives in separate functions instead of inside the classes.
To illustrate, suppose we have three data-only classes. The examples require Python 3.10 or later because of the float | None union syntax (and list[int], which needs 3.9 or later). functools.singledispatch itself has been available since Python 3.4.
|
|
To define preprocess, we decorate a base function with @functools.singledispatch and register one implementation per type with preprocess.register. The base function is the fallback for unregistered types.
|
|
Another behavior, such as validate, can be defined the same way, even in a separate module.
|
|
The pipeline then needs no isinstance checks.
|
|
There are a few benefits to this approach. Code for one behavior stays together instead of being spread across class files. Each behavior module imports only its own dependencies (a tokenizer, PIL, pandas), and the data classes stay light enough to share across training, serving, and evaluation. Subclasses also fall back to the parent’s registered implementation, so RGBImageSample(ImageSample) works without any new code.
The trade-off is that a new type, such as AudioSample, raises NotImplementedError until it is registered in every dispatch function.
#
Learn More
- functools.singledispatch. The official documentation, including how to register implementations with type annotations.
- Effective Python, 3rd Edition. Item 50 covers
functools.singledispatchwith a calculator AST example.