Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / Python

functools.singledispatch

Wybiera implementację według typu pierwszego argumentu pozycyjnego.

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

Składnia

@functools.singledispatch

Wybiera implementację według typu pierwszego argumentu pozycyjnego.

Od 3.11 adnotacja int | float przy register rejestruje tę samą funkcję osobno dla int i float, więc dispatch(int) i dispatch(float) zwracają ten sam obiekt. register przyjmuje typ jawnie lub wyprowadza go z adnotacji, a pierwotna funkcja obsługuje object. Uwzględnia nadklasy i zarejestrowane abstrakcyjne klasy bazowe. bool korzysta z int, więc True daje integer, a napis 3 daje other.

dispatch(type) pokazuje wybraną funkcję.

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"

Przykłady

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

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

Wynik

integer other

dispatch(type) pokazuje wybraną funkcję.

Źródła