Type Hinting Collections in Python
Python 3's function annotations provide a convenient way to specify the types of arguments and return values for functions. However, it was initially unclear whether this syntax could also be used to specify the types of items within collections, such as lists.
The current status, as of November 2015, is that Python 3.5 supports specifying the types of items within collections through the use of the typing module. PyCharm 5.0 and later versions fully support this feature, allowing type hints for collections to be visible in the editor.
For example, the following code defines a function that takes a list of strings as an argument:
from typing import List def do_something(l: List[str]): for s in l: s # str
PyCharm will recognize the type hint and provide autocompletion for the items within the list, as shown in the following screenshot:
[Image of PyCharm 5.0 code completion for type hinted collection]
It's important to note that prior to Python 3.5, specifying types within collections using annotations was not supported. As mentioned in the original answer, docstrings could be used as an alternative for type hinting. However, Python 3.5 now provides a more convenient and IDE-supported way to do this through the typing module.
The above is the detailed content of Can Python 3.5 Type Hint Collections?. For more information, please follow other related articles on the PHP Chinese website!