Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hinting generator in Python 3.6

People also ask

Does Python 3.6 support type hints?

This module supports type hints as specified by PEP 484 and PEP 526. The most fundamental support consists of the types Any , Union , Tuple , Callable , TypeVar , and Generic . For full specification please see PEP 484. For a simplified introduction to type hints see PEP 483.

Does Python have type hints?

Python's type hints provide you with optional static typing to leverage the best of both static and dynamic typing. Besides the str type, you can use other built-in types such as int , float , bool , and bytes for type hintings. To check the syntax for type hints, you need to use a static type checker tool.

Is type hinting good practice Python?

Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.


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.


This isn't a direct answer to the question, but I think it is a better solution.

I'm using the typing specification below, using Iterator[int] instead of Generator. The validation is OK. I think it is a lot clearer. It better describes the code intention and is recommended by Python docs.

from typing import Iterator

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

It would also allow future refactorings if you change your Generator for a list or other iterable.

I'm using Visual Studio Code with PyLance for typing validation. PyCharm mypy should have the same behavior.