Baza znanjaCentar za ispite
HRHrvatski
Odaberi jezik13

CKTIS / Python

functools.singledispatch

Bira implementaciju prema tipu prvog položajnog argumenta.

Verzija: Python 3.14; repository image, production runtime not attested

Sintaksa

@functools.singledispatch

Bira implementaciju prema tipu prvog položajnog argumenta.

Od inačice 3.11 register s anotacijom int | float registrira istu funkciju za int i float. dispatch(int) i dispatch(float) vraćaju isti objekt. register prima tip izričito ili iz anotacije, a izvorna funkcija obrađuje object. Uvažava pretke i registrirane apstraktne osnovne klase. bool koristi int pa True daje integer, a niz 3 daje other.

dispatch(type) pokazuje odabranu funkciju.

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"

Primjeri

import functools
@functools.singledispatch
def describe(value): return "other"
@describe.register(int)
def number(value): return "integer"

print(describe(True), describe("3"))

Rezultat

integer other

dispatch(type) pokazuje odabranu funkciju.

Izvori