Python's singledispatch: Generic Functions by Argument Type

This article explains how functools.singledispatch turns a chain of isinstance checks into an extensible generic function, how dispatch follows the MRO and abstract base classes, and which pitfalls and costs it carries.

A green tree python coiled in stacked loops around a tree trunk among leaves, with small mushrooms in the background
Photo by Jossuha Théophile on Unsplash

The present article addresses functools.singledispatch, the tool of the standard library that turns an ordinary function into a generic function, that is, a function whose implementation is chosen according to the type of its first argument. The need for it appears whenever a single operation must behave differently for unrelated types, such as dates, decimal numbers and sets, and those types cannot be modified to carry a method of their own. The usual answer is a chain of isinstance checks; the alternative examined here keeps each case in its own function and allows new cases to be added from other modules, which is the secret weapon of this article.

The isinstance Chain and Its Limits

A function that converts values into a form that json can serialize illustrates the problem. Each supported type requires a branch, and the following version handles three of them.

from datetime import date
from decimal import Decimal

def to_json(value):
    if isinstance(value, date):
        return value.isoformat()
    elif isinstance(value, Decimal):
        return str(value)
    elif isinstance(value, (set, frozenset)):
        return sorted(value)
    raise TypeError(f"cannot serialize {type(value).__name__}")

print(to_json(date(2025, 10, 18)))  # Output: 2025-10-18
print(to_json({3, 1, 2}))           # Output: [1, 2, 3]

The function works, but its structure has two weaknesses. Every new type lengthens a single function, and code that lives in another module, such as a library that defines its own value type, cannot add a branch without editing this function. In other words, the function is closed to extension, which contradicts the open/closed principle of software design.

Registering Implementations with singledispatch

The present section rewrites the same converter as a generic function. The decorator @singledispatch, introduced by PEP 443 in Python 3.4, marks the base function, and the method register of the resulting object adds one implementation per type; since Python 3.7, the type can be taken from the annotation of the first parameter.

import json
from datetime import date
from decimal import Decimal
from functools import singledispatch

@singledispatch
def to_json(value):
    raise TypeError(f"cannot serialize {type(value).__name__}")

@to_json.register
def _(value: date):
    return value.isoformat()

@to_json.register
def _(value: Decimal):
    return str(value)

@to_json.register(set)
@to_json.register(frozenset)
def _(value):
    return sorted(value)

print(to_json(Decimal("19.99")))  # Output: 19.99
print(json.dumps({"day": date(2025, 10, 18), "tags": {"b", "a"}}, default=to_json))
# Output: {"day": "2025-10-18", "tags": ["a", "b"]}

try:
    to_json(object())
except TypeError as error:
    print(error)  # Output: cannot serialize object

Each implementation is named _ because its name is irrelevant: what connects it to to_json is the registration, as the stacked decorators of the third implementation show. The generic function also fits directly into the parameter default of json.dumps, which calls it for every value that the module cannot serialize by itself. The mechanism is a decorator in the sense examined in the article devoted to decorators, with the difference that the returned object keeps a registry of implementations instead of wrapping a single function.

A module that defines a new type can now extend the converter without modifying it, simply by importing to_json and calling to_json.register with its own class. This is the property that the isinstance chain lacked.

Rally Point: What Happens to Unregistered Types

In strategy games, a rally point is the place to which newly produced units head when they have received no specific order. The base function of a generic function plays that role: it is registered for object, so any value whose type has no closer implementation ends there. Between the exact type and that final fallback, however, the dispatcher follows the method resolution order of the argument's class, and it also understands abstract base classes, as the following example shows.

from collections.abc import Mapping, Sequence
from functools import singledispatch

@singledispatch
def describe(value):
    return "something else"

@describe.register
def _(value: Sequence):
    return f"a sequence of length {len(value)}"

@describe.register
def _(value: Mapping):
    return f"a mapping with {len(value)} keys"

@describe.register
def _(value: str):
    return f"the text {value!r}"

print(describe([1, 2, 3]))      # Output: a sequence of length 3
print(describe((1,)))           # Output: a sequence of length 1
print(describe({"a": 1}))       # Output: a mapping with 1 keys
print(describe("abc"))          # Output: the text 'abc'
print(describe(42))             # Output: something else

print(describe.dispatch(list) is describe.dispatch(tuple))  # Output: True
print(sorted(cls.__name__ for cls in describe.registry))
# Output: ['Mapping', 'Sequence', 'object', 'str']

Neither list nor tuple is registered, yet both reach the implementation for Sequence, because they are virtual subclasses of that abstract base class. The string, which is also a sequence, receives its own implementation, since the dispatcher always prefers the most specific match. The method dispatch reveals which implementation a type would receive without calling it, and the mapping registry lists every registered type, two tools that are particularly useful for debugging.

Generic Methods with singledispatchmethod

A method cannot be decorated with singledispatch directly, because its first argument is self, whose type is always the same. Python 3.8 added functools.singledispatchmethod, which dispatches on the first argument after self and relies on the descriptor protocol, described in the article devoted to descriptors, to bind the method to its instance.

from functools import singledispatchmethod

class Formatter:
    def __init__(self, precision):
        self.precision = precision

    @singledispatchmethod
    def format(self, value):
        return str(value)

    @format.register
    def _(self, value: float):
        return f"{value:.{self.precision}f}"

    @format.register
    def _(self, value: list):
        return ", ".join(self.format(item) for item in value)

formatter = Formatter(precision=2)
print(formatter.format(3.14159))        # Output: 3.14
print(formatter.format([1.5, "x", 2]))  # Output: 1.50, x, 2

The implementation for list calls self.format for each item, so every element is dispatched again according to its own type. The state of the instance, here the precision, remains available to every implementation through self.

Pitfalls of Single Dispatch

This section identifies the limitations that most often produce unexpected results. Five pitfalls are distinguished, which are the following:

  1. Only the first positional argument counts. The other arguments play no part in the choice, and a call that passes the first argument by keyword fails with TypeError.
  2. Booleans are integers. Since bool is a subclass of int, True receives the implementation registered for int unless bool is registered explicitly.
  3. Silent replacement. Registering a second implementation for the same type replaces the first one without any warning.
  4. No parametrized generics. Annotations such as list[int] are rejected, because dispatch inspects the class of the argument, not the types of its contents; union types such as int | float, on the other hand, are accepted since Python 3.11.
  5. Overhead. Each call goes through a lookup in the registry, which costs more than a short isinstance chain.

The first three pitfalls are reproduced in the following example.

from functools import singledispatch

@singledispatch
def kind(value):
    return "other"

@kind.register
def _(value: int):
    return "integer"

print(kind(True))  # Output: integer

@kind.register
def _(value: int):
    return "replaced"

print(kind(1))  # Output: replaced

try:
    kind(value=1)
except TypeError as error:
    print(error)  # Output: kind requires at least 1 positional argument

The cost of the fifth pitfall can be measured with timeit, as the following example does with two equivalent functions.

import timeit

setup = """
from functools import singledispatch

@singledispatch
def generic(value):
    return "other"

@generic.register
def _(value: int):
    return "int"

@generic.register
def _(value: str):
    return "str"

def chain(value):
    if isinstance(value, int):
        return "int"
    elif isinstance(value, str):
        return "str"
    return "other"
"""

for call in ("generic('a')", "chain('a')"):
    seconds = min(timeit.repeat(call, setup=setup, number=1_000_000, repeat=5))
    print(f"{call}: {seconds * 1000:.0f} ns per call")
# Output (CPython 3.12, varies by machine): about 180 ns and 40 ns

The generic function is roughly four times slower than the two-branch chain on the machine used for this article. A difference of about 140 nanoseconds is irrelevant for a converter called once per value of a report, but it can matter inside a loop that runs millions of times.

When to Use singledispatch

Consequently, single dispatch is the appropriate tool when an operation must be defined outside the classes it applies to, and ordinary methods remain preferable when the classes belong to the same code base. A recurring line of a helmeted bounty hunter from a distant galaxy, "this is the way", summarizes the attitude that the following table proposes: the idiomatic choice depends on who owns the types.

Situation Recommended approach
The types belong to the same code base and can carry methods Ordinary methods and polymorphism
The types are built-in or come from other libraries functools.singledispatch
Other modules must be able to add support for new types functools.singledispatch with a documented register
The behaviour depends on the instance's state functools.singledispatchmethod
Only two or three types, in a performance-critical loop A short isinstance chain
The choice depends on several arguments Explicit logic, since the standard library offers no multiple dispatch

Conclusion

It is concluded that singledispatch replaces a growing chain of type checks with a registry of small implementations, chosen according to the class of the first argument and resolved through its method resolution order and abstract base classes. This magic makes a function open to extension from other modules, which is its main advantage over the isinstance chain, at the price of a measurable overhead and of a few rules that must be known, such as the silent replacement of registrations and the treatment of booleans as integers. Structural pattern matching, introduced in Python 3.10, offers another way to branch on the shape and type of a value inside a single function, and it is developed in a future article of this series.