Home > Backend Development > Python Tutorial > Can Python 3.5 Type Hint Collections?

Can Python 3.5 Type Hint Collections?

Patricia Arquette
Release: 2024-11-03 11:36:02
Original
327 people have browsed it

 Can Python 3.5 Type Hint Collections?

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template