CKTIS / Python
functools.singledispatch
Vybere implementaci podle typu prvního pozičního argumentu.
Verze: Python 3.14; repository image, production runtime not attested
Syntaxe
@functools.singledispatchVybere implementaci podle typu prvního pozičního argumentu.
Od verze 3.11 zaregistruje register s anotací int | float tutéž funkci pro int i float. dispatch(int) a dispatch(float) vrátí stejný objekt. register přijme typ výslovně nebo z anotace a původní funkce slouží pro object. Zohlední předky i registrované abstraktní základní třídy. bool použije int, proto True dá integer a řetězec 3 dá other.
dispatch(type) ukáže vybranou funkci.
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"
Příklady
import functools
@functools.singledispatch
def describe(value): return "other"
@describe.register(int)
def number(value): return "integer"
print(describe(True), describe("3"))
Výsledek
integer other
dispatch(type) ukáže vybranou funkci.