[Python-ideas] Proposal: Use mypy syntax for function annotations
Steven D'Aprano
steve at pearwood.info
Sun Aug 24 05:13:30 CEST 2014
On Sun, Aug 24, 2014 at 01:11:34PM +1200, Greg Ewing wrote:
> Georg Brandl wrote:
> >Another thought is whether, assuming
> >
> > class MyList(list):
> > ...
> >
> >the type "MyList[int]" would do the expected thing. (And if not,
> >how you would write the correct type generation code.)
>
> I would expect that to be a error, unless MyList were
> declared as accepting a type parameter, using whatever
> means is decided on for that in the type language.
I don't really understand what you're trying to say here, so I may be
misinterpreting you. I *think* that you're trying to say that for every
type in the standard library, and every class created by third parties
(including subclasses), the author will have to "declare" (in some
unknown sense) that it can be used for type annotations like MyList[T],
for some type T.
I expect that will be painful and unnecessary. I expect that if we go
down this path, somebody will have to add the appropriate code to the
metaclass of all types (i.e. type itself) so that AnyArbitraryType[spam]
will do the right thing without the author of AnyArbitraryType needing
to do any additional work.
This is not entirely uncharted territory. Mypy has blazed the trail for
us. The way I think Mypy works is that the classes in typing.py return
themselves when subscripted. The arguments to __getitem__ are ignored
except during static analysis. Here's the metaclass from Mypy:
class GenericMeta(type):
"""Metaclass for generic classes that support indexing by types."""
def __getitem__(self, args):
# Just ignore args; they are for compile-time checks only.
return self
https://github.com/JukkaL/mypy/blob/master/lib-typing/3.2/typing.py
As I understand it, we are considering two possibilities:
(1) all types are directly usable, so we can say
def func(param:list[int])->list:
This will require type to grow a __getitem__ method similar to
the metaclass above.
(2) Standard library types are not directly usable, you have to go
through the typing module, which has wrappers that include the
__getitem__ metaclass magic:
from typing import List
def func(param:List[int])->List:
There are pros and cons to both approaches.
--
Steven
More information about the Python-ideas
mailing list