Typed lazy iteration
A function yields a sequence lazily while exposing its produced element type.
Python · Type Alias
Generator is a generic type alias for annotating generator functions. Its parameters describe yielded values, values accepted by send(), and the final return value.
Generator is a generic type alias for describing generator functions. Its three parameters specify the type produced by yield, the type accepted by send, and the type returned when the generator terminates.
Generator[YieldType, SendType, ReturnType]| Name | Type | Description |
|---|---|---|
YieldType | type | Type produced by yield expressions. |
SendType | type | Type accepted by generator.send(). |
ReturnType | type | Type returned when the generator finishes. |
A parameterized typing description of a generator: Generator[YieldType, SendType, ReturnType].
from typing import Generator
def countdown(start: int) -> Generator[int, None, str]:
for value in range(start, 0, -1):
yield value
return "done"
iterator = countdown(3)
print(list(iterator))The annotation declares yielded integers, values sent into the generator as None, and a string returned when iteration finishes.
A function yields a sequence lazily while exposing its produced element type.
A coroutine-like generator receives values through send() and yields intermediate results.
A generator returns a meaningful result after its final yield.
Use Generator[YieldType, SendType, ReturnType]. For example, Generator[int, float, str] describes a generator that yields integers, accepts floats through send(), and returns a string when exhausted.
Follow-up: What does the second parameter describe? It is the type accepted by send(), not the type yielded by the generator.
The first parameter describes values produced by yield, the second describes values accepted by send(), and the third describes the generator's eventual return value. A return value is delivered through StopIteration when iteration ends.
Follow-up: How should an ordinary generator that never receives values be annotated? Use None as SendType, such as Generator[int, None, str].
Generator is intended for annotating generator functions and is parameterized as Generator[YieldType, SendType, ReturnType]. Type annotations are available to tools such as type checkers, IDEs, and linters, but Python does not enforce them during execution.
Follow-up: Does the annotation change generator execution? No; it supplies typing information only and does not alter runtime generator behavior.
IteratorAsyncGeneratorGenericTypeVar