Multiple dispatch in Python

2.8.0 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

Demonstrates defining multiple versions of a function using the `@dispatch` decorator, where the appropriate implementation is chosen based on the runtime type of the arguments. It also highlights the restriction on using positional arguments for dispatch.

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}")

view raw JSON →