Multiple dispatch
Multiple dispatch (also known as multimethods) is a programming concept that allows a function or method to be dynamically dispatched based on the runtime types of more than one of its arguments. The `multipledispatch` library provides an efficient Python implementation of this concept, performing static analysis to avoid conflicts and offering optional namespace support. The current stable version is 1.0.0, released in June 2023, with an infrequent release cadence.
Warnings
- gotcha The library may not always select the *most specific* implementation when multiple inheritance is involved or when method definitions create unexpected ambiguities. Some community reports suggest it might resolve based on definition order rather than strict specificity, which deviates from expected multiple dispatch behavior.
- gotcha AmbiguityWarning: If multiple equally specific implementations exist for a given call signature, `multipledispatch` raises an `AmbiguityWarning` at function definition time. If not resolved by adding a more specific signature, one of the competing functions will be selected "pseudo-randomly" at runtime.
- gotcha Performance with many signatures: Adding a new signature requires a full re-resolution of the entire function's dispatch table. This process can become slow and troublesome if a single dispatched function accumulates hundreds of type signatures.
- gotcha Global namespace conflicts: By default, `dispatch` uses a global namespace to register functions. In large applications or when integrating multiple libraries that both use `multipledispatch` without explicit namespaces, function name collisions can lead to difficult-to-track-down bugs or unexpected dispatch behavior.
- gotcha `multipledispatch`'s support for object-oriented programming paradigms, especially with class inheritance and complex Method Resolution Order (MRO), is limited. It may not behave as intuitively as other multiple dispatch implementations when dealing with subclasses and inherited methods.
Install
-
pip install multipledispatch
Imports
- dispatch
from multipledispatch import dispatch
Quickstart
from multipledispatch import dispatch
@dispatch(int, int)
def add(x, y):
return x + y
@dispatch(object, object)
def add(x, y):
return f"{x} + {y}"
print(add(1, 2)) # Expected: 3
print(add(1, 'hello')) # Expected: '1 + hello'