Python 3注释:键入提示指定类型的列表(PyCharm)

Eri*_* W. 93 python type-hinting pycharm python-3.x

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

int列表的伪python代码示例:

def my_func(l:list<int>):
    pass
Run Code Online (Sandbox Code Playgroud)



我知道可以使用Docstring ...

def my_func(l):
    """
    :type l: list[int]
    """
    pass
Run Code Online (Sandbox Code Playgroud)

...但如果有可能,我更喜欢注释样式.

Eri*_* W. 122

回答我自己的问题; 该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

  • FWIW(因为我不喜欢眯着眼睛看图像中模糊的文本):该图像的关键要点是“l:List [str]”。支持 alecxe 的答案,因为它以纯文本形式显示。 (4认同)
  • 从下面的答案来看,自Python3.9以来,使用“list”而不是“List”更受青睐 (2认同)

ale*_*cxe 52

现在Python 3.5正式推出,有类型提示支持模块 - typing以及List通用容器的相关"类型".

换句话说,现在你可以这样做:

from typing import List

def my_func(l: List[int]):
    pass
Run Code Online (Sandbox Code Playgroud)

  • 在 Python 3.9 中被取代。请参阅/sf/ask/1739774641/#62775680 (7认同)

Mis*_*agi 42

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

def my_func(l: list[int]):
    pass
Run Code Online (Sandbox Code Playgroud)

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

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

def my_func(l: list[int]):
    pass
Run Code Online (Sandbox Code Playgroud)


Gal*_*aph 36

更新 Python 3.9+

内置迭代不再需要从输入中导入

from . import Monitor


active_monitors: list[Monitor] = []
active_monitors: set[Monitor] = set()
monitor_pair: tuple[Monitor, Monitor] = (Monitor(), Monitor())
monitor_dict: dict[str, Monitor] = {'codename': Monitor()}
Run Code Online (Sandbox Code Playgroud)

原来的:

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()}]
Run Code Online (Sandbox Code Playgroud)

这目前正在使用 Python 3.6.4 在 PyCharm 上为我工作

Pycharm 中的示例图片