Type Hinting Collections of Specified Type in Python
Using Python 3's function annotations, it is possible to specify the type of items contained within a homogeneous collection for the purpose of type hinting in IDEs.
In the past, Python's type annotations did not support specifying types within collections. However, as of Python 3.5 and the inclusion of the typing module, this is now possible.
Syntax
To type hint a collection of a specific type, use the following syntax:
<code class="python">from typing import List def my_func(l: List[int]): pass</code>
In this example, the my_func function takes a list of integers as its argument.
IDE Support
JetBrains PyCharm 5.0 fully supports Python 3.5's type hints for collections, providing code completion and type checking.
Note:
As of August 2014, using Python 3 type annotations to specify types within collections was not possible. Formatted docstrings were the preferred method for type hinting collections. However, with the introduction of Python 3.5 and the typing module, type annotations are now the recommended approach.
The above is the detailed content of How to Type Hint Collections of Specified Types in Python?. For more information, please follow other related articles on the PHP Chinese website!