类型提示指定类型的集合 [英] Type hinting a collection of a specified type

查看:33
本文介绍了类型提示指定类型的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

def my_func(l:list):经过

我知道可以使用 Docstring...

def my_func(l):""":type l: 列表[int]"""经过

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

解决方案

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

更新 2

2015 年 9 月,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

Using Python 3's function annotations, it is possible to specify the type of items contained within a homogeneous list (or other collection) for the purpose of type hinting in PyCharm and other IDEs?

A pseudo-python code example for a list of int:

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

I know it's possible using Docstring...

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

... but I prefer the annotation style if it's possible.

解决方案

Answering my own question; the TLDR answer is No Yes.

Update 2

In September 2015, Python 3.5 was released with support for Type Hints and includes a new typing module. This allows for the specification of types contained within collections. As of November 2015, JetBrains PyCharm 5.0 fully supports Python 3.5 to include Type Hints as illustrated below.

Update 1

As of May 2015, PEP0484 (Type Hints) has been formally accepted. The draft implementation is also available at github under ambv/typehinting.

Original Answer

As of Aug 2014, I have confirmed that it is not possible to use Python 3 type annotations to specify types within collections (ex: a list of strings).

The use of formatted docstrings such as reStructuredText or Sphinx are viable alternatives and supported by various IDEs.

It also appears that Guido is mulling over the idea of extending type annotations in the spirit of mypy: http://mail.python.org/pipermail/python-ideas/2014-August/028618.html

这篇关于类型提示指定类型的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆