The if/elif isinstance mess you keep writing

Every Python dev eventually writes some version of this:

def render(value):
    if isinstance(value, int):
        return str(value)
    elif isinstance(value, str):
        return value.upper()
    elif isinstance(value, (list, tuple)):
        return ", ".join(map(str, value))
    else:
        return f"{value!r}"

It works, but it grows sideways, it’s hard to test a single branch in isolation, and adding a new type means editing the one function everyone else also touches. functools.singledispatch lets you register handlers per type and keep the dispatch table open for extension.

The dispatcher and its registrations

Decorate a base implementation with @singledispatch. It runs for any type you haven’t registered. Then stack @<func>.register decorators — one per type — to add specialized handlers:

from functools import singledispatch

@singledispatch
def render(value):
    return f"{value!r}"          # fallback for object

@render.register
def _(value: int):
    return str(value)

@render.register
def _(value: str):
    return value.upper()

@render.register
def _(value: list):
    return ", ".join(map(str, value))

print(render(42))            # 42
print(render("hi"))          # HI
print(render([1, 2, 3]))     # 1, 2, 3
print(render({"a": 1}))      # {'a': 1}   <- object fallback

The function name passed to .register is irrelevant (use _); only the type annotation on that handler’s first parameter decides what it handles.

Gotcha 1: dispatch is on the FIRST argument only

singledispatch inspects type() of the first positional argument — nothing else. A type on the second argument, or on a keyword argument, is invisible to the dispatcher:

@singledispatch
def tag(first, second):
    return f"default first={type(first).__name__}"

@tag.register
def _(first: int, second):
    return "int-first"

print(tag(1, "x"))     # int-first
print(tag("x", 1))     # default first=str   <- second arg ignored

If you need to dispatch on a later argument, reorder the call so the deciding value is first, or use singledispatchmethod (below) where self is skipped and dispatch happens on the second argument.

Gotcha 2: it uses type(), so register ABCs yourself

Dispatch compares the exact runtime type, not isinstance. A tuple is not a list, so a handler registered for list won’t catch it. To catch a whole family, register the ABC from collections.abc:

from collections.abc import Sequence

@render.register
def _(value: Sequence):
    return ", ".join(map(str, value))

print(render((1, 2)))        # 1, 2     <- tuple is a Sequence
print(render({"a": 1}))      # {'a': 1} <- dict is NOT a Sequence

Forget to register the ABC and you silently fall through to the base implementation — a quiet bug, not an error.

Gotcha 3: the most-specific type wins

When more than one registered type matches via inheritance, the most derived one is chosen. Registering a subclass after its parent overrides the parent for that subclass:

class MyList(list):
    pass

@render.register
def _(value: MyList):
    return "MYLIST:" + ", ".join(map(str, value))

print(render(MyList([1, 2])))   # MYLIST:1, 2   <- beats the list handler
print(render([1, 2]))           # 1, 2          <- still the plain list handler

This is what makes singledispatch safer than a hand-rolled if/elif ladder: the ladder’s branch order is a footgun, the registered registry resolves by MRO.

Gotcha 4: register() returns the function

.register(type) (or the decorator form) returns the handler, so you can re-assign or stack it — and re-registering a type replaces the previous handler for that type:

@render.register(int)
def _alt_int(value):
    return f"INT:{value}"

print(render(7))   # INT:7   <- replaced the earlier int handler

Use this deliberately; an accidental duplicate registration silently shadows the old one.

Gotcha 5: in a class, use singledispatchmethod

On a method, the first argument is self, so plain singledispatch would dispatch on the instance, not the payload. singledispatchmethod skips self and dispatches on the second argument:

from functools import singledispatchmethod

class Handler:
    @singledispatchmethod
    def emit(self, value):
        return f"default {type(value).__name__}"

    @emit.register
    def _(self, value: bytes):
        return value.decode()

h = Handler()
print(h.emit(b"hi"))   # hi
print(h.emit("hi"))    # default str

When NOT to use it

  • Dispatching on value (not type), e.g. status codes — a dict lookup is clearer.
  • Needing to match multiple arguments or a Union — singledispatch is single-argument by design; combine with typing guards or a library like plum/multipledispatch.
  • Hot inner loops where type() lookup per call matters — the overhead is small but real.

Cheat sheet

  • @singledispatch base = fallback for object; registrations typed by annotation.
  • Dispatch = type(first_positional_arg); keyword/second args don’t count.
  • Register ABCs (Sequence, Mapping, …) to catch families.
  • Most-derived registered type wins (MRO resolution).
  • .register() returns the handler → re-registering a type replaces it.
  • Methods: @singledispatchmethod, dispatch on the 2nd arg (self skipped).
  • func.registry holds the mapping; func.dispatch(type) fetches the handler.