singledispatchmethod Dispatches Class Methods

Register singledispatchmethod overloads by argument type, dispatch through a class instance, and fall back to a base implementation.

PythonData Integrity

Code

pythonsnippet
32 lines
from functools import singledispatchmethod


class Formatter:
    @singledispatchmethod
    def format(self, value: object) -> str:
        return "unsupported:" + type(value).__name__

    @format.register(int)
    def _format_int(self, value: int) -> str:
        return "int:" + str(value)

    @format.register(list)
    def _format_list(self, value: list) -> str:
        parts = [self.format(item) for item in value]
        return "list:[" + ", ".join(parts) + "]"

    @format.register(str)
    def _format_str(self, value: str) -> str:
        return "str:" + value.upper()


def main() -> None:
    formatter = Formatter()
    print(formatter.format(42))
    print(formatter.format("hello"))
    print(formatter.format([1, "a", 2.5]))
    print(formatter.format({"x": 1}))


if __name__ == "__main__":
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

int:42
str:HELLO
list:[int:1, str:A, unsupported:float]
unsupported:dict

How the snippet works

Structurally, expect the class Formatter and the functions format, _format_int, _format_list and _format_str and nothing else.

Points of care

  • No install step: all APIs used ship with the platform.

Using it

Entry signature: def format(self, value: object) -> str

main sequences format; executing the file runs that flow once.

Key statements

def main() -> None:
    formatter = Formatter()
    print(formatter.format(42))
    print(formatter.format("hello"))
    print(formatter.format([1, "a", 2.5]))
    print(formatter.format({"x": 1}))
def _format_list(self, value: list) -> str:
    parts = [self.format(item) for item in value]
    return "list:[" + ", ".join(parts) + "]"
def _format_int(self, value: int) -> str:
    return "int:" + str(value)

Interactive Tools for This Topic

FAQ

How do you run singledispatchmethod Dispatches Class Methods?
Execute it straight away — the program needs nothing beyond the runtime.