Multimethod
Multimethod provides a decorator for adding multiple argument dispatching to functions in Python. It aims for simplicity and speed, utilizing type annotations to create a multimethod object that registers functions based on argument types. The library supports various type hints and advanced dispatching rules. It is currently at version 2.0.2 and has an active development and release cadence, with several releases per year.
Warnings
- breaking Version 2.0 removed the `overload` decorator and the mechanism for resolving ambiguity using positional distance. Code relying on these features will break.
- gotcha Keyword-only parameters are supported for type annotation, but `multimethod` (the main decorator) itself dispatches solely on positional arguments. Keyword arguments are ignored during the dispatching process. If keyword dispatch is needed, consider `multidispatch`.
- gotcha Typing aliases (e.g., `typing.List`, `typing.Dict`) do not consistently support the `issubclass` relation, which `multimethod` uses for type resolution. This can lead to unexpected dispatch behavior.
- breaking Starting with version 2.0.0, `multimethod` requires Python 3.10 or newer. Older versions (e.g., 1.x) supported Python 3.6 or 3.7 and up.
Install
-
pip install multimethod
Imports
- multimethod
from multimethod import multimethod
- multimeta
from multimethod import multimeta
- multidispatch
from multimethod import multidispatch
Quickstart
from multimethod import multimethod
@multimethod
def func(x: int, y: float):
return f"Int and Float: {x} + {y}"
@multimethod
def func(x: float, y: int):
return f"Float and Int: {x} + {y}"
@multimethod
def func(x: str, y: str):
return f"Strings: {x} {y}"
print(func(1, 2.0))
print(func(3.0, 4))
print(func("Hello", "World"))