Type hinting generator in Python 3.6
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.
![Jinho Choi](https://lh4.googleusercontent.com/-1zlxAlnRDaE/AAAAAAAAAAI/AAAAAAAAABk/y7_Z4DW4Pdg/photo.jpg?sz=256)
Jinho Choi
Updated on October 30, 2021Comments
-
Jinho Choi over 2 years
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:So, I'm wondering if this is actually an error or an unsupported feature in PyCharm.
-
defance over 2 yearsI am not sure why this got downvoted. The python doc itself states, that is it possible to use
Iterator[YieldType]
orIterable[YieldType]
for generators, which yield only. See docs.python.org/3.6/library/typing.html#typing.Generator -
thiagola92 about 2 years
from collections.abc import Iterator
is the new preferable way. See docs.python.org/3.10/library/typing.html#typing.Iterable