类型提示指定类型的列表


128

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

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

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

我知道有可能使用Docstring ...

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

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


您是否尝试过在功能注释中使用相同的格式?发生了什么?
jonrsharpe 2014年

@jonrsharpe它应该引发错误,因为type object is not subscriptable在定义函数时。显然,您可以使用字符串:def my_func(L: 'list[int]')但是我不知道PyCharm是否会在解析文档字符串时对其进行解析……
Bakuriu 2014年

@Bakuriu是的,我的意思是'list[int]',如果不清楚的话,我们深表歉意。
jonrsharpe 2014年

似乎PyCharm不会像文档字符串那样解析它。
Eric W.

Answers:


161

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

更新2

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

使用类型提示的PyCharm 5.0代码完成

更新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


更新:似乎包含对通用类型的支持的类型提示已进入PEP484 python.org/dev/peps/pep-0484
Eric W.

74

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

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

from typing import List

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

10

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中的示例图片



3

从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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.