Multiple dispatch in Python
Plum-dispatch is a Python library that provides a powerful and Pythonic implementation of multiple dispatch, allowing functions to behave differently based on the types of multiple arguments. Its design philosophy is inspired by Julia's approach to multiple dispatch, and version 2.x is powered by the `beartype` library for enhanced performance. The library is actively maintained, with its current version being 2.8.0, and has seen consistent updates.
Warnings
- breaking Plum (version 2.x) relies on positional arguments for dispatch. Keyword arguments are explicitly NOT used in the decision-making for which method to call. Positional arguments without a default value must always be given positionally.
- breaking Import paths have changed. All imports for Plum's public API should now go directly through the `plum` package (e.g., `from plum import dispatch`). Sub-module imports are no longer recommended or supported.
- breaking Plum 2.x dropped support for Python 3.9.
- gotcha Using parametric types (e.g., `List[int]`, `Tuple[str, int]`) for dispatch can incur a significant performance hit due to the need to check every element's type.
- gotcha Plum is often recommended over `multipledispatch` due to being more featureful, having better support for class inheritance, and correctly handling method precedence (choosing the most specific method).
Install
-
pip install plum-dispatch
Imports
- dispatch
from plum import dispatch
Quickstart
from numbers import Number
from plum import dispatch
@dispatch
def process(x: str):
return f"Processing string: {x}"
@dispatch
def process(x: int):
return f"Processing integer: {x}"
@dispatch
def process(x: Number):
return f"Processing a generic number: {x}"
assert process("hello") == "Processing string: hello"
assert process(123) == "Processing integer: 123"
assert process(1.0) == "Processing a generic number: 1.0"
try:
process(x=123) # This will fail due to keyword argument dispatch rule
except Exception as e:
print(f"Caught expected error: {type(e).__name__}: {e}")