【问题标题】:Type hinting a collection of a specified type类型提示指定类型的集合
【发布时间】:2014-09-11 07:10:15
【问题描述】:

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

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

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

我知道可以使用 Docstring...

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

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

【问题讨论】:

  • 你试过在函数注解中使用相同的格式吗?发生了什么?
  • @jonrsharpe 它应该会引发错误,因为type object is not subscriptable 在定义函数时。显然你可以使用一个字符串:def my_func(L: 'list[int]') 但我不知道 PyCharm 在解析文档字符串时是否会解析它...
  • @Bakuriu 是的,我的意思是'list[int]',如果不清楚,请道歉。
  • 看起来 PyCharm 不会像解析文档字符串那样解析它。

标签: python python-3.x type-hinting python-typing


【解决方案1】:

类型 cmets 自 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 上为我工作

【讨论】:

    【解决方案2】:

    从 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
    

    【讨论】:

    • 这现在应该是公认的答案了。
    • 作为@Splines 评论的确认,这现在应该是 Python > 3.9 的答案
    【解决方案3】:

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

    更新 2

    2015 年 9 月,Python 3.5 发布,支持类型提示,包括 new typing module。这允许指定集合中包含的类型。截至 2015 年 11 月,JetBrains PyCharm 5.0 完全支持 Python 3.5,包括如下所示的类型提示。

    更新 1

    截至 2015 年 5 月,PEP0484 (Type Hints) 已正式接受。还可以通过github under 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
    • FWIW(因为我不喜欢眯着眼看图像中的模糊文本):从该图像中获得的关键信息是l: List[str]。赞成 alecxe 的答案,因为它以纯文本形式显示。
    【解决方案4】:

    现在 Python 3.5 正式发布,有类型提示支持模块 - typing 和相关的 List 通用容器的“类型”。

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

    from typing import List
    
    def my_func(l: List[int]):
        pass
    

    【讨论】:

      【解决方案5】:

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

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

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

      http://mypy-lang.org/

      【讨论】:

        猜你喜欢
        • 2018-09-10
        • 2022-07-28
        • 2021-06-21
        • 2023-03-29
        • 2014-01-30
        • 2016-08-17
        • 2016-10-16
        相关资源
        最近更新 更多