'What is the return type hint of a generator function?
I'm trying to write a :rtype: type hint for a generator function. What is the type it returns?
For example, say I have this functions which yields strings:
def read_text_file(fn):
"""
Yields the lines of the text file one by one.
:param fn: Path of text file to read.
:type fn: str
:rtype: ???????????????? <======================= what goes here?
"""
with open(fn, 'rt') as text_file:
for line in text_file:
yield line
The return type isn't just a string, it's some kind of iterable of strings? So I can't just write :rtype: str. What's the right hint?
Solution 1:[1]
Solution 2:[2]
As of Python 3.9, you can annotate a generator using the Generator[YieldType, SendType, ReturnType] generic type from collections.abc. For example:
from collections.abc import Generator
def echo_round() -> Generator[int, float, str]:
sent = yield 0
while sent >= 0:
sent = yield round(sent)
return 'Done'
In earlier versions of Python you can import the Generator class from the typing module. Alternatively, Iterable[YieldType] or Iterator[YieldType] from typing can be used.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Druta Ruslan |
| Solution 2 |
