Python Glossary Русский

Python 3.4+functoolsterm

functools.singledispatch

dispatch

Decorator for writing generic functions that dispatch on the type of the first argument. Implementations are registered with @func.register.

Syntax

@functools.singledispatch
@func.register(type)

Dispatch looks only at the first argument, and only if it is passed positionally — pass it by keyword and you get a TypeError; the remaining arguments never affect the choice. Lookup follows the MRO, so a subclass picks up the implementation registered for its base class or ABC; since 3.7 register can read the type off the annotation, and since 3.11 union annotations such as int | float work too. It does not cover methods — use singledispatchmethod there.

Examples

from functools import singledispatch
@singledispatch
def process(arg):
    return f'unknown: {arg}'
@process.register(int)
def _(arg): return f'int: {arg * 2}'
@process.register(str)
def _(arg): return f'str: {arg.upper()}'
print(process(5))  # → int: 10
print(process('hi'))  # → str: HI
print(process(3.14))  # → unknown: 3.14
print(process([1, 2]))  # → unknown: [1, 2]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy