Skip to main content

Live, Learn, and Lung

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class TextSample:
    def __init__(self, text: str) -> None:
        self.text = text

class ImageSample:
    def __init__(self, pixels: list[int]) -> None:
        self.pixels = pixels

class TabularSample:
    def __init__(self, row: list[float | None]) -> None:
        self.row = row

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import functools
from typing import Any

@functools.singledispatch
def preprocess(sample: Any) -> list[Any]:
    raise NotImplementedError

@preprocess.register(TextSample)
def _(sample: TextSample) -> list[str]:
    return sample.text.lower().split()

@preprocess.register(ImageSample)
def _(sample: ImageSample) -> list[float]:
    return [p / 255 for p in sample.pixels]

@preprocess.register(TabularSample)
def _(sample: TabularSample) -> list[float]:
    mean = sum(sample.row) / len(sample.row)
    return [x - mean for x in sample.row]

Another behavior, such as validate, can be defined the same way, even in a separate module.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@functools.singledispatch
def validate(sample: Any) -> bool:
    raise NotImplementedError

@validate.register(TextSample)
def _(sample: TextSample) -> bool:
    return len(sample.text) > 0

@validate.register(ImageSample)
def _(sample: ImageSample) -> bool:
    return all(0 <= p <= 255 for p in sample.pixels)

@validate.register(TabularSample)
def _(sample: TabularSample) -> bool:
    return None not in sample.row

The pipeline then needs no isinstance checks.

1
2
3
4
5
6
def run(samples: list[Any]) -> list[list[Any]]:
    return [preprocess(s) for s in samples if validate(s)]

samples = [TextSample("Hello World"), ImageSample([0, 128, 255])]
print(run(samples))
# [['hello', 'world'], [0.0, 0.5019607843137255, 1.0]]

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