[Python-ideas] Multiple dispatch (was Re: PEP 484 change proposal: Allowing <at> overload outside stub files

Nick Coghlan ncoghlan at gmail.com
Sat Jan 23 21:45:05 EST 2016


On 24 January 2016 at 07:12, Stefan Krah <skrah.temporarily at gmail.com> wrote:
> Nick Coghlan <ncoghlan at ...> writes:
>> You're already going to have to allow this for single lines to handle
>> Py2 compatible annotations, so it seems reasonable to also extend it
>> to handle overloading while you're still figuring out a native syntax
>> for that.
>
> I find that https://pypi.python.org/pypi/multipledispatch looks quite
> nice:
>
>>>> from multipledispatch import dispatch
>>>> @dispatch(int, int)
> ... def add(x, y):
> ...      return x + y
> ...
>>>> @dispatch(float, float)
> ... def add(x, y):
> ...     return x + y
> ...
>>>> add(1, 2)
> 3
>>>> add(1.0, 2.0)
> 3.0
>>>> add(1.0, 2)
> Traceback (most recent call last):
>   File
> [cut because gmane.org is inflexible]
> line 155, in __call__
>     func = self._cache[types]
> KeyError: (<class 'float'>, <class 'int'>)

Right, the Blaze folks have been doing some very nice work in that
area. One of the projects building on multipledispatch is the Odo
network of data conversion operations: https://github.com/blaze/odo

They do make the somewhat controversial design decision to make
dispatch operations process global by default [1], rather than scoping
by module. On the other hand, the design also makes it easy to define
your own dispatch namespace, so the default orthogonality with the
module system likely isn't a problem in practice, and the lack of
essential boilerplate does make it very easy to use in contexts like
an IPython notebook.

There is one aspect that still requires runtime stack introspection
[2], and that's getting access to the class scope in order to
implicitly make method dispatch specific to the class defining the
methods. It's the kind of thing that makes me wonder whether we should
be exposing a thread-local variable somewhere with a "class namespace
stack" that made it possible to:

- tell that you're currently running in the context of a class definition
- readily get access to the namespace of the innermost class currently
being defined

Cheers,
Nick.

[1] http://multiple-dispatch.readthedocs.org/en/latest/design.html#namespaces-and-dispatch
[2] https://github.com/mrocklin/multipledispatch/blob/master/multipledispatch/core.py

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list