4.4. Typing Generator
All Generators are Iterators
4.4.1. SetUp
Import from
typingorcollections.abccollections.abcshould be preferred
>>> from typing import Generator, Iterator
>>> from collections.abc import Iterator, Generator
4.4.2. Iterator
All Generators are Iterators
Iterator[yield_type]
>>> def run() -> Iterator:
... yield 1
>>> def run() -> Iterator[int]:
... yield 1
4.4.3. Generator
Generator
>>> def run() -> Generator:
... yield 1
4.4.4. Generator Yield Type
Generator[yield_type, send_type, return_type]
>>> def run() -> Generator[int, None, None]:
... yield 1
4.4.5. Generator Send Type
Generator[yield_type, send_type, return_type]
>>> def run() -> Generator[None, str, None]:
... data = yield
... print(data)
4.4.6. Generator Return Type
Generator[yield_type, send_type, return_type]
>>> def run() -> Generator[int, bool, str]:
... yield 1 # int
... data = yield # (expected) bool
... return 'done' # str
4.4.7. Further Reading
Since Python 3.9: PEP 585 -- Type Hinting Generics In Standard Collections
https://docs.python.org/3/library/typing.html#typing.Iterable
https://docs.python.org/3/library/typing.html#typing.Generator