0
# Multiple Dispatch
1
2
Multiple dispatch implementation for Python that enables function dispatching based on the types of all non-keyword arguments. Unlike Python's built-in single dispatch, this library dispatches on all arguments, supporting inheritance, instance methods, union types, variadic signatures, and comprehensive conflict resolution.
3
4
## Package Information
5
6
- **Package Name**: multipledispatch
7
- **Language**: Python
8
- **Installation**: `pip install multipledispatch`
9
10
## Core Imports
11
12
```python
13
from multipledispatch import dispatch, Dispatcher
14
```
15
16
For advanced usage:
17
18
```python
19
from multipledispatch import (
20
dispatch, Dispatcher,
21
MDNotImplementedError,
22
halt_ordering, restart_ordering
23
)
24
```
25
26
For conflict analysis and utilities:
27
28
```python
29
from multipledispatch.conflict import (
30
supercedes, ambiguous, ambiguities,
31
AmbiguityWarning
32
)
33
from multipledispatch.utils import typename, str_signature
34
from multipledispatch.variadic import Variadic, isvariadic
35
```
36
37
## Basic Usage
38
39
```python
40
from multipledispatch import dispatch
41
42
# Basic function dispatch
43
@dispatch(int, int)
44
def add(x, y):
45
return x + y
46
47
@dispatch(float, float)
48
def add(x, y):
49
return x + y
50
51
@dispatch(str, str)
52
def add(x, y):
53
return x + y
54
55
# Usage
56
print(add(1, 2)) # Uses int, int implementation -> 3
57
print(add(1.0, 2.0)) # Uses float, float implementation -> 3.0
58
print(add("a", "b")) # Uses str, str implementation -> "ab"
59
60
# Class method dispatch
61
class Vector:
62
def __init__(self, data):
63
self.data = data
64
65
@dispatch('Vector', 'Vector')
66
def __add__(self, other):
67
return Vector([a + b for a, b in zip(self.data, other.data)])
68
69
@dispatch('Vector', (int, float))
70
def __add__(self, scalar):
71
return Vector([x + scalar for x in self.data])
72
73
v1 = Vector([1, 2, 3])
74
v2 = Vector([4, 5, 6])
75
result = v1 + v2 # Vector addition
76
scaled = v1 + 2 # Scalar addition
77
```
78
79
## Architecture
80
81
The dispatch system is built on three core components:
82
83
- **Dispatcher**: Manages type signatures and method resolution for a single function name
84
- **Global Namespace**: Default registry for all dispatched functions with automatic conflict detection
85
- **Signature Ordering**: Topological ordering system that resolves inheritance and prevents ambiguity
86
87
The library performs static analysis to detect conflicts at registration time rather than runtime, ensuring predictable behavior and optimal performance through caching.
88
89
## Capabilities
90
91
### Core Dispatch Functionality
92
93
Essential dispatching features including the main dispatch decorator, Dispatcher class for programmatic dispatch management, and comprehensive type system support with inheritance, unions, and method dispatch.
94
95
```python { .api }
96
def dispatch(*types, **kwargs):
97
"""
98
Decorator for creating dispatched functions.
99
100
Parameters:
101
- *types: Type signatures for dispatch
102
- namespace: dict (optional) - Custom namespace for dispatch isolation
103
104
Returns:
105
Decorator function that registers implementations
106
"""
107
108
class Dispatcher:
109
"""
110
Dispatcher for managing multiple implementations of a function.
111
"""
112
def __init__(self, name, doc=None):
113
"""
114
Initialize dispatcher.
115
116
Parameters:
117
- name: str - Name of the dispatched function
118
- doc: str (optional) - Documentation string
119
"""
120
121
def register(self, *types, **kwargs):
122
"""
123
Register new implementation for given types.
124
125
Parameters:
126
- *types: Type signature
127
- **kwargs: Additional options
128
129
Returns:
130
Decorator function
131
"""
132
```
133
134
[Core Dispatch](./core-dispatch.md)
135
136
### Advanced Features
137
138
Advanced dispatching capabilities including conflict resolution, variadic dispatch, custom namespaces, error handling, and signature analysis tools for complex dispatch scenarios.
139
140
```python { .api }
141
class Variadic:
142
"""
143
Type for variadic argument signatures.
144
Usage: Variadic[int] for variable number of int arguments
145
"""
146
147
def isvariadic(obj):
148
"""
149
Check if type represents variadic signature.
150
151
Parameters:
152
- obj: Type to check
153
154
Returns:
155
bool: True if type is variadic
156
"""
157
158
class MDNotImplementedError(NotImplementedError):
159
"""
160
Exception raised when no suitable dispatch implementation is found.
161
"""
162
```
163
164
[Advanced Features](./advanced-features.md)
165
166
## Types
167
168
```python { .api }
169
# Type aliases for dispatch signatures
170
TypeSignature = tuple # Tuple of types for dispatch
171
NamespaceDict = dict # Namespace dictionary for dispatch isolation
172
173
# Union type specification (tuple of types)
174
UnionType = tuple # e.g., (int, float) for int OR float
175
176
# Variadic type specification
177
VariadicType = type # Created via Variadic[type] or Variadic[(type1, type2)]
178
```