[Python-ideas] PEP 484 change proposal: Allowing @overload outside stub files

Nick Coghlan ncoghlan at gmail.com
Fri Jan 22 23:04:43 EST 2016


On 23 January 2016 at 06:00, Guido van Rossum <guido at python.org> wrote:
> Ben Darnell (Tornado lead) brought up a good use case for allowing @overload
> in regular Python files.
>
> There's some discussion (some old, some new) here:
> https://github.com/ambv/typehinting/issues/72
>
> I now propose to allow @overload in non-stub (i.e. .py) files, but with the
> following rule: a series of @overload-decorated functions must be followed
> by an implementation function that's not @overload-decorated. Calling an
> @overload-decorated function is still an error (I propose NotImplemented).
> Due to the way repeated function definitions with the same name replace each
> other, leaving only the last one active, this should work. E.g. for
> Tornado's utf8() the full definition would look like this:
>
> @overload
> def utf8(value: None) -> None: ...
> @overload
> def utf8(value: bytes) -> bytes: ...
> @overload
> def utf8(value: str) -> bytes: ...  # or (unicode)->bytes, in PY2
> def utf8(value):
>     # Real implementation goes here.

I share Andrew's concerns about the lack of integration between this
and functools.singledispatch, so would it be feasible to apply the
"magic comments" approach here, similar to the workarounds for
variable annotations and Py2 compatible function annotations?

That is, would it be possible to use a notation like the following?:

    def utf8(value):
        # type: (None) -> None
        # type: (bytes) -> bytes
        # type: (unicode) -> bytes
        ...

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.

Regards,
Nick.

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


More information about the Python-ideas mailing list