类型提示指定类型的列表

问题:类型提示指定类型的列表

使用Python 3的功能注释,可以指定包含在同类列表(或其他集合)中的项的类型,以便在PyCharm和其他IDE中进行类型提示。

一个int列表的伪python代码示例:

def my_func(l:list<int>):
    pass

我知道有可能使用Docstring …

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

…但是我更喜欢注释样式。

Using Python 3’s function annotations, it is possible to specify the type of items contained within a homogeneous list (or other collection) for the purpose of type hinting in PyCharm and other IDEs?

A pseudo-python code example for a list of int:

def my_func(l:list<int>):
    pass

I know it’s possible using Docstring…

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

… but I prefer the annotation style if it’s possible.


回答 0

回答我自己的问题;TLDR的答案是“

更新2

在2015年9月,Python 3.5发行了对Type Hints的支持,并包含一个新的打字模块。这允许指定集合中包含的类型。截至2015年11月,JetBrains PyCharm 5.0完全支持Python 3.5包含类型提示,如下所示。

更新1

截至2015年5月,PEP0484(类型提示)已被正式接受。草案的实现也可以在github的ambv / typehinting下找到

原始答案

自2014年8月起,我已经确认无法使用Python 3类型注释在集合中指定类型(例如:字符串列表)。

诸如reStructuredText或Sphinx之类的格式化文档字符串的使用是可行的替代方法,并且受各种IDE支持。

看来,Guido还本着mypy的精神考虑了扩展类型注释的想法:http ://mail.python.org/pipermail/python-ideas/2014-August/028618.html

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.

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


回答 1

现在Python 3.5正式发布了,这里有Type Hints支持模块- typing以及相关的List通用容器 “类型”。

换句话说,现在您可以执行以下操作:

from typing import List

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

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 List

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

回答 2

PEP 484起已添加类型注释

from . import Monitor
from typing import List, Set, Tuple, Dict


active_monitors = [] # type: List[Monitor]
# or
active_monitors: List[Monitor] = []

# bonus
active_monitors: Set[Monitor] = set()
monitor_pair: Tuple[Monitor, Monitor] = (Monitor(), Monitor())
monitor_dict: Dict[str, Monitor] = {'codename': Monitor()}

# nested
monitor_pair_list: List[Dict[str, Monitor]] = [{'codename': Monitor()}]

目前,这对于使用Python 3.6.4的PyCharm来说是有用的

Pycharm中的示例图片

Type comments have been added since PEP 484

from . import Monitor
from typing import List, Set, Tuple, Dict


active_monitors = [] # type: List[Monitor]
# or
active_monitors: List[Monitor] = []

# bonus
active_monitors: Set[Monitor] = set()
monitor_pair: Tuple[Monitor, Monitor] = (Monitor(), Monitor())
monitor_dict: Dict[str, Monitor] = {'codename': Monitor()}

# nested
monitor_pair_list: List[Dict[str, Monitor]] = [{'codename': Monitor()}]

This is currently working for me on PyCharm with Python 3.6.4

Example Picture in Pycharm


回答 3

在BDFL的支持下,现在几乎可以确定python(可能是3.5)将通过函数注释为类型提示提供标准化的语法。

https://www.python.org/dev/peps/pep-0484/

正如PEP中所引用的那样,有一个名为mypy的实验型类型检查器(有点像pylint,但对于类型而言)已经使用此标准,并且不需要任何新语法。

http://mypy-lang.org/

With support from the BDFL, it’s almost certain now that python (probably 3.5) will provide a standardized syntax for type hints via function annotations.

https://www.python.org/dev/peps/pep-0484/

As referenced in the PEP, there is an experimental type-checker (kind of like pylint, but for types) called mypy that already uses this standard, and doesn’t require any new syntax.

http://mypy-lang.org/


回答 4

从Python 3.9开始,内置类型在类型注释方面是通用的(请参阅PEP 585)。这允许直接指定元素的类型:

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

各种工具可能早于Python 3.9支持此语法。如果在运行时未检查注释,则使用引号或语法有效__future__.annotations

# quoted
def my_func(l: 'list[int]'):
    pass
# postponed evaluation of annotation
from __future__ import annotations

def 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.

# quoted
def my_func(l: 'list[int]'):
    pass
# postponed evaluation of annotation
from __future__ import annotations

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