Annotate generator return types
A function lazily produces records or values without building a list first.
Python · Type Alias
Iterator[T] annotates an iterator that yields values of type T. Modern Python code should use collections.abc.Iterator[T], while typing.Iterator remains as a compatibility form.
Iterator[T] describes an iterator that produces values of type T. Use it to annotate iterator-producing functions, including generators; the modern form comes from collections.abc rather than the deprecated typing alias.
collections.abc.Iterator[T]| Name | Type | Description |
|---|---|---|
T | type parameter | The type of each value produced by the iterator. |
An iterator producing values of type T.
from collections.abc import Iterator
def numbers() -> Iterator[int]:
yield 1
yield 2
for number in numbers():
print(number)The generator yields integers, and its return annotation describes the iterator's item type.
A function lazily produces records or values without building a list first.
A custom object implements the iterator protocol and yields a known value type.
An API accepts a one-pass stream of typed values.
Iterator[T] is a generic annotation for an iterator whose produced values have type T. A generator that only yields values can use it as its return annotation.
Follow-up: When would Iterable[T] be preferable? Use Iterable[T] when callers only need to iterate and the implementation need not expose iterator-specific behavior.
A generator function can be annotated with Iterator[T] when it yields values of type T. Calling the function returns a generator iterator rather than a materialized collection.
Follow-up: What is the practical consequence of returning an iterator? Consumption is typically one-pass, so callers should not assume they can restart it without creating another iterator.
The modern generic alias is collections.abc.Iterator[T]. The typing module's Iterator is retained for compatibility but is deprecated because the collections.abc form supports subscription.
Follow-up: How would you annotate an iterator of an unconstrained type? Use Iterator[Any] or leave the item type broad according to the intended static contract.
collections.abc.Iteratorcollections.abc.Iterabletyping.Iterabletyping.GeneratorStopIterationiterator.__iter__()iterator.__next__()