How to type hint a generator in Python 3?

You need to import the typing module. 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

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. Try switching to version 2016.3.2 and you might be fine. Unfortunately this is a well-known bug, as per @AshwiniChaudhary comment.

More, the reported issue (for the last version of PyCharm) was submitted on December, last year. They probably fixed it and pushed the modifications into the same version.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)