简体   繁体   English

在python 3.6中输入提示生成器

[英]Type hinting generator in python 3.6

According to PEP-484 , we should be able to type hinting a generator function as follows: 根据PEP-484 ,我们应该可以输入提示生成器函数,如下所示:

from typing import Generator

def generate() -> Generator[int, None, None]:
    for i in range(10):
        yield i

for i in generate():
    print(i)

However, the list comprehension gives the following error in PyCharm. 但是,列表推导在PyCharm中给出以下错误。

Expected 'collections.Iterable', got 'Generator[int, None, None]' instead less... (⌘F1)

Any idea why PyCharm is considering this as error? 知道为什么PyCharm将此视为错误吗? Thank you. 谢谢。


A few clarification after reading some answers. 阅读一些答案后的一些澄清。 I am using PyCharm Community Edition 2016.3.2 (the latest version) and have imported the typing.Generator (updated in the code). 我正在使用PyCharm Community Edition 2016.3.2(最新版本)并导入了typing.Generator (在代码中更新)。 The above code runs just fine, but PyCharm considers this an error: 上面的代码运行得很好,但PyCharm认为这是一个错误:

在此输入图像描述

So, I'm wondering if this is actually an error or an unsupported feature in PyCharm. 所以,我想知道这实际上是PyCharm中的错误还是不支持的功能。

You need to import the typing module. 您需要导入typing模块。 As per docs: 根据文档:

The return type of generator functions can be annotated by the generic type Generator[yield_type, send_type, return_type] provided by typing.py module 生成器函数的返回类型可以通过typing.py模块提供的泛型类型Generator[yield_type, send_type, return_type]进行typing.py

Try this way instead: 请尝试这种方式:

from typing import Generator


def generate() -> Generator[int, None, None]:
    for i in range(10):
        yield i

The above will have the desired result: 以上将有所需的结果:

l = [i for i in generate()]

Output: 输出:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


As pointed out in the comments, you might not use the last version of PyCharm. 正如评论中指出的那样,您可能不会使用最新版本的PyCharm。 Try switching to version 2016.3.2 and you might be fine. 尝试切换到2016.3.2版本,你可能没问题 Unfortunately this is a well-known bug, as per @AshwiniChaudhary comment. 不幸的是,根据@AshwiniChaudhary的评论,这是一个众所周知的错误。

More, the reported issue (for the last version of PyCharm) was submitted on December, last year. 更多,报道的问题(最新版本的PyCharm)于去年12月提交。 They probably fixed it and pushed the modifications into the same version. 他们可能修复了它并将修改推送到同一版本。

As commented by Oleksandr Dashkov , I tried the same code with Pycharm 2017.1 EAP, which handles this annotation correctly. 正如Oleksandr Dashkov评论的那样 ,我使用Pycharm 2017.1 EAP尝试了相同的代码,它正确地处理了这个注释。 I guess this feature will be integrated in the next official version of PyCharm. 我想这个功能将被集成到PyCharm的下一个正式版本中。 Thanks to everyone. 谢谢大家。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM