Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / Python

functools.singledispatch

Escolhe a implementação pelo tipo do primeiro argumento posicional.

Versão: Python 3.14; repository image, production runtime not attested

Sintaxe

@functools.singledispatch

Escolhe a implementação pelo tipo do primeiro argumento posicional.

Desde a versão 3.11, com a anotação int | float, register regista a mesma função para int e float. dispatch(int) e dispatch(float) devolvem o mesmo objeto. register aceita o tipo explícito ou inferido da anotação e a original trata object. Considera superclasses e bases abstratas registadas. bool usa int, portanto True dá integer e a cadeia 3 dá other.

dispatch(type) mostra a função escolhida.

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"

Exemplos

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

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

Resultado

integer other

dispatch(type) mostra a função escolhida.

Fontes