[Python-ideas] Adding Type[C] support to PEP 484 and typing.py

Guido van Rossum guido at python.org
Thu May 12 14:49:27 EDT 2016


There's one new feature I'd like to add to PEP 484 and the typing.py module
that will go out with Python 3.5.2.

There's a long discssion in https://github.com/python/typing/issues/107,
but I think I can explain the proposal very quickly.

There's currently no good way to talk about class objects. If you have a
function argument that's a class (as opposed to an instance) the only
annotation you can give it is `type`. But I've encountered this pattern
quite frequently, and what people invariably want to say is "it's a
subclass of this here class C." Example:

class User: ...
class TeamUser(User): ...
class ProUser(User): ...
def new_user(user_class: Type[User]) -> User: ...

The proposal is to let you spell that explicitly by setting the type or
such an argument to `Type[C]`. The type checker will then understand that
if you call it, the result is an instance of C. It will also know about all
the class methods defined on C.

There are some subtleties, e.g. in the above example we would actually like
to know that the return type varies with the argument type:

joe = new_user(ProUser)  # Really, joe is a ProUser, not just a User

This can be done using a type variable, e.g.

U = TypeVar('U', bound=User)
def new_user(user_class: Type[U]) -> U: ...
joe = new_user(ProUser)

The key part I want to settle quickly is the notation: I need to add a
special generic `class Type` to typing.py so that we can start implementing
this in mypy.

Any objections? Or should I just go ahead and add the text to PEP 484 and
post the diff to python-dev?

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160512/517bc5d4/attachment.html>


More information about the Python-ideas mailing list