CKTIS / Python
functools.singledispatch
Dispatches a generic function according to the runtime type of its first argument.
Version: Python 3.14; repository image, production runtime not attested
Syntax
@functools.singledispatchDispatches a generic function according to the runtime type of its first argument.
A subclass can use a registered superclass implementation when no more specific registration exists.
Select an implementation by the first positional argument's type. Register handlers with register(type) or an inferred annotation; the undecorated original serves object. Selection considers ancestor types and registered abstract base classes. bool reaches the int implementation since it subclasses int, whereas a string uses the default. dispatch(type) exposes the chosen function. Since 3.11 a registered int | float annotation installs the same handler under both concrete type keys in registry and dispatch.
from functools import singledispatch
@singledispatch
def label(x): return "object"
@label.register(int)
def integer(x): return "int"
assert label(True) == "int" and label("1") == "object"
assert label.dispatch(bool) is integer and label.registry[int] is integer
@label.register
def numeric(x: int | float): return "number"
assert label.dispatch(int) is label.registry[float] is numeric
assert label(2) == label(2.5) == "number"
Examples
import functools
@functools.singledispatch
def describe(value): return "other"
@describe.register(int)
def number(value): return "integer"
print(describe(True), describe("3"))
Result
integer other
Select an implementation by the first positional argument's type. Register handlers with register(type) or an inferred annotation; the undecorated original serves object. Selection considers ancestor types and registered abstract base classes. bool reaches the int implementation since it subclasses int, whereas a string uses the default. dispatch(type) exposes the chosen function. Since 3.11 a registered int | float annotation installs the same handler under both concrete type keys in registry and dispatch.