File: design.rst

package info (click to toggle)
python-multipledispatch 1.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 272 kB
  • sloc: python: 1,116; makefile: 141
file content (197 lines) | stat: -rw-r--r-- 4,591 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
Design
======

Types
-----

::

    signature  :: [type]
                  a list of types

    Dispatcher :: {signature: function}
                  A mapping of type signatures to function implementations

    namespace  :: {str: Dispatcher}
                  A mapping from function names, like 'add', to Dispatchers

Dispatchers
-----------

A ``Dispatcher`` object stores and selects between different
implementations of the same abstract operation. It selects the
appropriate implementation based on a signature, or list of types. We
build one dispatcher per abstract operation.

.. code::

    f = Dispatcher('f')

At the lowest level we build normal Python functions and then add them
to the ``Dispatcher``.

.. code::

    >>> def inc(x):
    ...     return x + 1

    >>> def dec(x):
    ...     return x - 1

    >>> f.add((int,), inc)    # f increments integers
    >>> f.add((float,), dec)  # f decrements floats

    >>> f(1)
    2

    >>> f(1.0)
    0.0

Internally ``Dispatcher.dispatch`` selects the function implementation.

.. code::

    >>> f.dispatch(int)
    <function __main__.inc>

    >>> f.dispatch(float)
    <function __main__.dec>

For notational convenience dispatchers leverage Python's decorator
syntax to register functions as we define them.

.. code::

    f = Dispatcher('f')

    @f.register(int)
    def inc(x):
        return x + 1

    @f.register(float)
    def dec(x):
        return x - 1

This is equivalent to the form above.
It adheres to the standard implemented by ``functools.singledispatch`` in
Python 3.4 (although the "functional form" of ``register`` is not supported).

As in ``singledispatch``, the ``register`` decorator returns the
undecorated function, which enables decorator stacking.

.. code::

    @f.register(str)
    @f.register(tuple)
    def rev(x):
        return x[::-1]


The Dispatcher creates a detailed docstring automatically.
To add a description of the multimethod itself,
provide it when creating the ``Dispatcher``.

.. code::

    >>> f = Dispatcher('f', doc="Do something to the argument")

    >>> @f.register(int)
    ... def inc(x):
    ...     "Integers are incremented"
    ...     return x + 1

    >>> @f.register(float)
    ... def dec(x):
    ...     "Floats are decremented"
    ...     return x - 1

    >>> @f.register(str)
    ... @f.register(tuple)
    ... def rev(x):
    ...     # no docstring
    ...     return x[::-1]

    >>> print(f.__doc__)
    Multiply dispatched method: f

    Do something to the argument

    Inputs: <float>
    ----------------
    Floats are decremented

    Inputs: <int>
    --------------
    Integers are incremented

    Other signatures:
        str
        tuple

Namespaces and ``dispatch``
---------------------------

The ``dispatch`` decorator hides the creation and manipulation of
``Dispatcher`` objects from the user.

.. code::

    # f = Dispatcher('f')  # no need to create Dispatcher ahead of time

    @dispatch(int)
    def f(x):
        return x + 1

    @dispatch(float)
    def f(x):
        return x - 1

The ``dispatch`` decorator uses the name of the function to select the
appropriate ``Dispatcher`` object to which it adds the new
signature/function. When it encounters a new function name it creates a
new ``Dispatcher`` object and stores name/Dispatcher pair in a namespace
for future reference.

.. code::

    # This creates and stores a new Dispatcher('g')
    # namespace['g'] = Dispatcher('g')
    # namespace['g'].add((int,), g)
    @dispatch(int)
    def g(x):
        return x ** 2

We store this new ``Dispatcher`` in a *namespace*. A namespace is simply
a dictionary that maps function names like ``'g'`` to dispatcher objects
like ``Dispatcher('g')``.

By default ``dispatch`` uses the global namespace in
``multipledispatch.core.global_namespace``. If several projects use this
global namespace unwisely then conflicts may arise, causing difficult to
track down bugs. Users who desire additional security may establish
their own namespaces simply by creating a dictionary.

.. code::

    my_namespace = dict()

    @dispatch(int, namespace=my_namespace)
    def f(x):
        return x + 1

To establish a namespace for an entire project we suggest the use of
``functools.partial`` to bind the new namespace to the ``dispatch``
decorator.

.. code::

    from multipledispatch import dispatch
    from functools import partial

    my_namespace = dict()
    dispatch = partial(dispatch, namespace=my_namespace)

    @dispatch(int)  # Uses my_namespace rather than the global namespace
    def f(x):
        return x + 1