Method Dispatch

5.0.1 · active · verified Fri Apr 17

methoddispatch provides a decorator similar to `functools.singledispatch` but specifically designed for dispatching class methods based on the type of their arguments. It extends Python's built-in single dispatch functionality to work seamlessly within classes, supporting different implementations for various argument types. The current version is 5.0.1, with an irregular release cadence driven by feature enhancements and Python version compatibility.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a class method with the `@methoddispatch` decorator and register different implementations for specific argument types. The generic `process` method serves as the fallback, while `int`, `str`, and `list` types have specialized implementations.

from methoddispatch import methoddispatch

class MyClass:
    @methoddispatch
    def process(self, arg):
        return f"Processing generic {type(arg).__name__}: {arg}"

    @process.register(int)
    def _(self, arg: int):
        return f"Processing int: {arg * 2}"

    @process.register(str)
    def _(self, arg: str):
        return f"Processing str: {arg.upper()}"

    @process.register(list) # Will match list[int] as per v5.0.0 behavior
    def _(self, arg: list):
        return f"Processing list of length: {len(arg)}"

# Example usage
instance = MyClass()
print(instance.process(10))
print(instance.process("hello"))
print(instance.process([1, 2, 3]))
print(instance.process(3.14))
print(instance.process([4, 5])) # Demonstrates list[int] matching list handler

view raw JSON →