Reputation: 38540
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?
Upvotes: 167
Views: 95601
Reputation: 4883
Comparing Iterator
with Generator
...
The docs define collections.abc.Generator
as an "ABC for generator classes that implement ... the send()
, throw()
and close()
methods".
So I use collections.abc.Iterator[ReturnType]
for a 'plain' generator, and reserve collections.abc.Generator
for cases where I have implemented send()
/throw()
/close()
.
Upvotes: 19
Reputation: 150031
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.
Upvotes: 101