CKTIS / Python
functools.singledispatchmethod
Dispatches a method using its first argument after the instance or class.
Version: Python 3.14; repository image, production runtime not attested
Syntax
@functools.singledispatchmethodDispatches a method using its first argument after the instance or class.
A registered specialized method handles matching argument types while other types continue through the default method.
Dispatch a method by its first positional input after the bound instance or class. Registration adds a type-specific method, while other types fall back to the original. When combined with classmethod put singledispatchmethod outermost to keep register available. The sample formats integer 15 as 0xf, while the string uses 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"
Examples
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"))
Result
0xf other
Dispatch a method by its first positional input after the bound instance or class. Registration adds a type-specific method, while other types fall back to the original. When combined with classmethod put singledispatchmethod outermost to keep register available. The sample formats integer 15 as 0xf, while the string uses other.