Videos
You need to import the typing module. As per the documentation:
The return type of generator functions can be annotated by the generic type
Generator[yield_type, send_type, return_type]provided bytyping.pymodule
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 Ashwini Chaudhary's comment.
More, the reported issue (for the last version of PyCharm) was submitted in December 2016. 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 the Python documentation.
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.
If you are using Python 3.10 or later, change the import command above to:
from collections.abc import Iterator
Using type as a keyword argument to a function will mask the built-in function "type" within the scope of the function. So while doing so does not raise a SyntaxError, it is not considered good practice, and I would avoid doing so.
Neither. It's not a reserved word (a list of which can be found at http://docs.python.org/reference/lexical_analysis.html#keywords ), but it's generally a bad idea to shadow any builtin.
If I want to type-hint a generator function and a generator (for example, a and b below) using the typing module, which types should I use?
def gen():
yield 'Hello world!'
a = gen # a is a generator function
b = gen() # b is a generator