首页 文章

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

提问于
浏览
51

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

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

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

我知道可以使用Docstring ...

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

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

4 回答

  • 4

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

    Update 2

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

    PyCharm 5.0 Code Completion using Type Hints

    Update 1

    截至2015年5月,PEP0484 (Type Hints)已正式被接受 . 该实施草案也可在github under ambv/typehinting获取 .

    Original Answer

    截至2014年8月,我已确认无法使用Python 3类型注释来指定集合中的类型(例如:字符串列表) .

    使用格式化的文档字符串(如reStructuredText或Sphinx)是可行的替代方案,并受各种IDE的支持 .

    看来,Guido正在考虑以mypy的精神扩展类型注释的想法:http://mail.python.org/pipermail/python-ideas/2014-August/028618.html

  • 79

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

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

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

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

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

    正如PEP中所提到的,有一个名为mypy的实验类型检查器(类似于pylint,但对于类型)已经使用了这个标准,并且不需要任何新的语法 .

    http://mypy-lang.org/

  • 25

    PEP 484以来已添加类型注释

    active_monitors = [] # type: List[Monitor]
    

    这个目前在PyCharm上使用Python 3.6.4

    Example Picture in Pycharm

相关问题