Base de connaissancesCentre d’examen
FRFrançais
Choisir la langue13

CKTIS / Python

functools.singledispatchmethod

Choisit la méthode selon le premier argument positionnel après self ou cls.

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

Syntaxe

@functools.singledispatchmethod

Choisit la méthode selon le premier argument positionnel après self ou cls.

register ajoute une variante typée, sans enregistrement adapté la méthode originale s’applique. Avec classmethod placer singledispatchmethod à l’extérieur pour conserver register.

L’entier 15 donne 0xf et la chaîne 15 donne other.

from functools import singledispatchmethod
class Parse:
    @singledispatchmethod
    @classmethod
    def read(cls, arg): return "other"
    @read.register
    @classmethod
    def _(cls, arg: int): return cls.__name__
assert Parse.read(True) == "Parse" and Parse.read("1") == "other"

Exemples

import functools
class Formatter:
    @functools.singledispatchmethod
    def show(self, value): return "other"
    @show.register(int)
    def integer(self, value): return hex(value)

f = Formatter()
print(f.show(15), f.show("15"))

Résultat

0xf other

L’entier 15 donne 0xf et la chaîne 15 donne other.

Sources