Generators
A basic generator that only yields values can be annotated as having a returntype of either Iterator[YieldType]
or Iterable[YieldType]
. For example:
- def squares(n: int) -> Iterator[int]:
- for i in range(n):
- yield i * i
If you want your generator to accept values via the send()
method or returna value, you should use theGenerator[YieldType, SendType, ReturnType]
generic type instead. For example:
- def echo_round() -> Generator[int, float, str]:
- sent = yield 0
- while sent >= 0:
- sent = yield round(sent)
- return 'Done'
Note that unlike many other generics in the typing module, the SendType
ofGenerator
behaves contravariantly, not covariantly or invariantly.
If you do not plan on receiving or returning values, then set the SendType
or ReturnType
to None
, as appropriate. For example, we could haveannotated the first example as the following:
- def squares(n: int) -> Generator[int, None, None]:
- for i in range(n):
- yield i * i
This is slightly different from using Iterable[int]
or Iterator[int]
,since generators have close()
, send()
, and throw()
methods thatgeneric iterables don’t. If you will call these methods on the returnedgenerator, use the Generator
type instead of Iterable
or Iterator
.