ID EN
Functools

singledispatchmethod

Python 3.11

Transform a method into a single-dispatch generic function.

Syntax

PYTHON
class functools.singledispatchmethod(func)

Examples

Example 1
PYTHON
class Negator:
    @singledispatchmethod
    def neg(self, arg):
        raise NotImplementedError("Cannot negate a")

    @neg.register
    def _(self, arg: int):
        return -arg

    @neg.register
    def _(self, arg: bool):
        return not arg
Example 2
PYTHON
class Negator:
    @singledispatchmethod
    @classmethod
    def neg(cls, arg):
        raise NotImplementedError("Cannot negate a")

    @neg.register
    @classmethod
    def _(cls, arg: int):
        return -arg

    @neg.register
    @classmethod
    def _(cls, arg: bool):
        return not arg

See Also

single-dispatch generic function @classmethod @staticmethod @abstractmethod