CKTIS / Python
functools.singledispatch
Vyberie implementáciu podľa typu prvého pozičného argumentu.
Verzia: Python 3.14; repository image, production runtime not attested
Syntax
@functools.singledispatchVyberie implementáciu podľa typu prvého pozičného argumentu.
Od verzie 3.11 zaregistruje register s anotáciou int | float tú istú funkciu pre int aj float. dispatch(int) a dispatch(float) vrátia ten istý objekt. register prijme typ výslovne alebo z anotácie a pôvodná funkcia slúži pre object. Zohľadní predkov aj registrované abstraktné základné triedy. bool použije int, preto True dá integer a reťazec 3 dá other.
dispatch(type) ukáže vybranú funkciu.
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"
Príklady
import functools
@functools.singledispatch
def describe(value): return "other"
@describe.register(int)
def number(value): return "integer"
print(describe(True), describe("3"))
Výsledok
integer other
dispatch(type) ukáže vybranú funkciu.