[Python] How to type hint a generator in Python 3?

Discussão em 'Python' iniciado por Stack, Março 16, 2025.

  1. Stack

    Stack Membro Participativo

    According to PEP-484, we should be able to type hinting a generator function as follows:

    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.


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

    Any idea why PyCharm is considering this as error?


    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). The above code runs just fine, but PyCharm considers this an error:

    [​IMG]

    So, I'm wondering if this is actually an error or an unsupported feature in PyCharm.

    Continue reading...

Compartilhe esta Página