[Python-ideas] PEP 484 change proposal: Allowing <at> overload outside stub files

Andrew Barnert abarnert at yahoo.com
Mon Jan 25 16:03:49 EST 2016


On Jan 23, 2016, at 13: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'>)

Of course you still have to work out how that would fit with type annotations. Presumably you could just move the dispatched types from the decorator to the annotations, and add a return type on each overload. And you could make the dispatch algorithm ignore element types in generic types (so add(a: Sequence[T], b: Sequence[T]) gets called on any pair of Sequences).

But even then, it's hard to imagine how a type checker could understand your code unless it had special-case code for this special decorator.

Not to mention that you're not supposed to runtime-dispatch on typing.Sequence (isinstance and issubclass only work by accident), but you can't genericize collections.abc.Sequence.

Plus, as either Guido or Jukka pointed out earlier, you may want to specify that Sequence[T] normally returns T but Sequence[Number] always returns float or something; at runtime, those are the same type, so they have to share a single implementation, which takes you right back to needing a way to specify overloads for the type checker.

Still, I would love to see someone take that library and mypy and experiment with making them work together and solving all of these problems.

(As a side note, every time I look at this stuff, I start thinking I want type computation so I can specify that add(a: Sequence[T], b: Sequence[U]) -> Sequence[decltype(T + U)], until I spend a few minutes trying to find a way to write that that isn't as horrible as C++ without introducing all of Haskell into Python, and then appreciating again why maybe building the simple thing first was a good idea...)


More information about the Python-ideas mailing list