类型提示指定类型的集合

问题描述 投票:0回答:5

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

int 列表的伪 python 代码示例:

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

我知道可以使用 Docstring...

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

...但如果可能的话我更喜欢注释风格。

python python-3.x type-hinting python-typing
5个回答
304
投票

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

更新2

2015 年 9 月,Python 3.5 发布,支持类型提示,并包含一个新的打字模块。这允许指定集合中包含的类型。截至 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


188
投票

自从 Python 3.5 正式发布以来,就有了类型提示支持模块 -

typing
以及相关的
List
通用容器的“类型”。

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

from typing import List

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

自 Python 3.9 起已弃用,现在您可以直接使用内置的

list
代替
typing.List


162
投票

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

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

这也扩展到标准库的大多数其他容器类型,例如

collections.deque
collections.abc.Mapping


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

由于 PEP 585,

typing
中与标准库类型相对应的大多数助手已被弃用,例如
typing.List
typing.Deque
typing.Mapping
。仅当需要与 3.9 之前的 Python 版本兼容时才应使用它们。


58
投票

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 上工作

Example Picture in Pycharm


4
投票

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

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

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

http://mypy-lang.org/

© www.soinside.com 2019 - 2024. All rights reserved.