Type hinting a collection of a specified type Type hinting a collection of a specified type python python

Type hinting a collection of a specified type


Answering my own question; the TLDR answer is No Yes.

Update 2

In September 2015, Python 3.5 was released with support for Type Hints and includes a new typing module. This allows for the specification of types contained within collections. As of November 2015, JetBrains PyCharm 5.0 fully supports Python 3.5 to include Type Hints as illustrated below.

PyCharm 5.0 Code Completion using Type Hints

Update 1

As of May 2015, PEP0484 (Type Hints) has been formally accepted. The draft implementation is also available at github under ambv/typehinting.

Original Answer

As of Aug 2014, I have confirmed that it is not possible to use Python 3 type annotations to specify types within collections (ex: a list of strings).

The use of formatted docstrings such as reStructuredText or Sphinx are viable alternatives and supported by various IDEs.

It also appears that Guido is mulling over the idea of extending type annotations in the spirit of mypy: http://mail.python.org/pipermail/python-ideas/2014-August/028618.html


Now that Python 3.5 is officially out, there is the Type Hints supporting module - typing and the relevant List "type" for the generic containers.

In other words, now you can do:

from typing import Listdef my_func(l: List[int]):    pass


As of Python 3.9, builtin types are generic with respect to type annotations (see PEP 585). This allows to directly specify the type of elements:

def my_func(l: list[int]):    pass

Various tools may support this syntax earlier than Python 3.9. When annotations are not inspected at runtime, the syntax is valid using quoting or __future__.annotations.

# quoteddef my_func(l: 'list[int]'):    pass
# postponed evaluation of annotationfrom __future__ import annotationsdef my_func(l: list[int]):    pass