← retour aux snippets

functools.singledispatchmethod: méthodes génériques

Spécialiser une méthode selon le type du premier argument.

objectif

Spécialiser une méthode selon le type du premier argument.

code minimal

from functools import singledispatchmethod
class P:
    @singledispatchmethod
    def show(self, x): return "obj"
    @show.register
    def _(self, x: int): return "int"
    @show.register
    def _(self, x: str): return "str"
print(P().show(1) == "int" and P().show("a") == "str")  # attendu: True

utilisation

from functools import singledispatchmethod
class C:
    @singledispatchmethod
    def f(self, x): return type(x).__name__
print(C().f(3) == "int")

variante(s) utile(s)

from functools import singledispatchmethod
class C:
    @singledispatchmethod
    def f(self, x): return "base"
    @f.register
    def _(self, x: bytes): return "bytes"
print(C().f(b"x") == "bytes")

notes

  • Le dispatch se base sur l’annotation de type du 1er paramètre réel.
  • Combinez avec Protocols pour APIs extensibles.