对指定类型的集合进行类型提示
- 2025-01-10 08:47:00
- admin 原创
- 100
问题描述:
使用 Python 3 的函数注释,是否可以指定同类列表(或其他集合)中包含的项目的类型,以便在 PyCharm 和其他 IDE 中进行类型提示?
int 列表的伪 Python 代码示例:
def my_func(l:list<int>):
pass
我知道使用 Docstring 是可能的......
def my_func(l):
"""
:type l: list[int]
"""
pass
...但如果可能的话,我更喜欢注释样式。
解决方案 1:
截至 2015 年 5 月,PEP 484 (Type Hints)已正式被接受。 实施草案也可在github 的 ambv/typehinting 下找到。
2015 年 9 月,Python 3.5 发布,支持类型提示并包含一个新的类型模块。这允许指定集合中包含的类型。截至 2015 年 11 月,JetBrains PyCharm 5.0 完全支持 Python 3.5 以包含类型提示,如下所示。
from typing import List
def do_something(l: List[str]):
for s in l:
s # str
原始答案
截至 2014 年 8 月,我已确认无法使用 Python 3 类型注释来指定集合内的类型(例如:字符串列表)。
使用格式化的文档字符串(例如 reStructuredText 或 Sphinx)是可行的替代方案,并且受到各种 IDE 的支持。
Guido 似乎也在考虑以 mypy 的精神扩展类型注释:http://mail.python.org/pipermail/python-ideas/2014-August/028618.html
解决方案 2:
从 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 版本兼容时才应使用它们。
解决方案 3:
自 Python 3.5 正式发布以来,就出现了 Type Hints 支持模块 -以及通用容器的typing
相关“类型”。List
换句话说,现在你可以这样做:
from typing import List
def my_func(l: List[int]):
pass
自 Python 3.9 以来,此功能已弃用,现在您可以直接使用内置功能list
代替typing.List
。
解决方案 4:
自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()}]
这目前在 PyCharm 和 Python 3.6.4 上对我有用
解决方案 5:
在 BDFL 的支持下,现在几乎可以肯定,python(可能是 3.5)将通过函数注释为类型提示提供标准化语法。
https://www.python.org/dev/peps/pep-0484/
正如 PEP 中所引用的,有一个名为 mypy 的实验性类型检查器(有点像 pylint,但用于类型),它已经使用了此标准,并且不需要任何新的语法。