[Python-checkins] cpython (merge 3.5 -> default): Add typing.Generator docs, by Michael Lee. (Merge 3.5->3.6)
guido.van.rossum
python-checkins at python.org
Fri Aug 5 15:57:50 EDT 2016
https://hg.python.org/cpython/rev/f10029fea6ee
changeset: 102542:f10029fea6ee
parent: 102540:fe189b8bd3ab
parent: 102541:b5403f416836
user: Guido van Rossum <guido at dropbox.com>
date: Fri Aug 05 12:57:38 2016 -0700
summary:
Add typing.Generator docs, by Michael Lee. (Merge 3.5->3.6)
files:
Doc/library/typing.rst | 29 +++++++++++++++++++++++++++++
1 files changed, 29 insertions(+), 0 deletions(-)
diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst
--- a/Doc/library/typing.rst
+++ b/Doc/library/typing.rst
@@ -561,6 +561,35 @@
.. class:: Generator(Iterator[T_co], Generic[T_co, T_contra, V_co])
+ A generator can be annotated by the generic type
+ ``Generator[YieldType, SendType, ReturnType]``. 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``
+ of :class:`Generator` behaves contravariantly, not covariantly or
+ invariantly.
+
+ If your generator will only yield values, set the ``SendType`` and
+ ``ReturnType`` to ``None``::
+
+ def infinite_stream(start: int) -> Generator[int, None, None]:
+ while True:
+ yield start
+ start += 1
+
+ Alternatively, annotate your generator as having a return type of
+ ``Iterator[YieldType]``::
+
+ def infinite_stream(start: int) -> Iterator[int]:
+ while True:
+ yield start
+ start += 1
+
.. class:: io
Wrapper namespace for I/O stream types.
--
Repository URL: https://hg.python.org/cpython
More information about the Python-checkins
mailing list