[Python-Dev] PEP 484 -- proposal to allow @overload in non-stub files
Guido van Rossum
guido at python.org
Wed Oct 21 18:58:17 EDT 2015
More information about the Python-Dev mailing list
Wed Oct 21 18:58:17 EDT 2015
- Previous message (by thread): [Python-Dev] PEP-8 wart... it recommends short names because of DOS
- Next message (by thread): [Python-Dev] PEP 484 -- proposal to allow @overload in non-stub files
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
PEP 484 (Type Hinting) currently disallows @overload outside stub files. The hope was that a PEP for multi-dispatch would emerge, but that's been slow coming. Meanwhile, over in https://github.com/ambv/typehinting/issues/72 a proposal has emerged to allow @overload in regular modules, as long as it is followed by a non-overloaded definition that serves as the default/fallback. A motivating example is __getitem__, which is often overloaded for item access and slicing. In stubs, you can use: class Foo(Generic[T]): @overload def __getitem__(self, i: int) -> T: ... @overload def __getitem__(self, s: slice) -> Foo[T]: ... (Note that the '...' are part of the actual code -- an ellipsis is how you represent the body of all functions in stub files.) However, in source files the best you can do is: class Foo(Generic[T]): def __getitem__(self, i: Union[int, slice]) -> Union[T, List[T]]: ... which will require unacceptable casts at every call site. You can work around it by having a stub file but that's cumbersome if this is the only reason to have one. The proposal is to allow this to be written as follows in implementation (non-stub) modules: class Foo(Generic[T]): @overload def __getitem__(self, i: int) -> T: ... @overload def __getitem__(self, s: slice) -> Foo[T]: ... def __getitem__(self, x): <actual implementation goes here> The actual implementation must be last, so at run time it will override the definition. It has to use isinstance() to distinguish the cases. A type checker would have to recognize this as a special case (so as not to complain about the non-overloaded version). Jukka thinks it would be about a day's work to implement in mypy; the work in typing.py would be a few minutes. Thoughts? -- --Guido van Rossum (python.org/~guido) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20151021/8eaa40d3/attachment.html>
- Previous message (by thread): [Python-Dev] PEP-8 wart... it recommends short names because of DOS
- Next message (by thread): [Python-Dev] PEP 484 -- proposal to allow @overload in non-stub files
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-Dev mailing list