Skip to content

Commit 7d701eb

Browse files
encukoublaisepStanFromIrelandhugovk
authored
gh-141984: Move generator iterator reference out of syntax docs (GH-154884)
Co-authored-by: Blaise Pabon <blaise@gmail.com> Co-authored-by: Stan Ulbrych <stan@python.org> Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
1 parent 3c7e975 commit 7d701eb

3 files changed

Lines changed: 296 additions & 184 deletions

File tree

Doc/library/stdtypes.rst

Lines changed: 282 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -891,10 +891,12 @@ many numeric contexts, ``False`` and ``True`` behave like the integers 0 and 1,
891891
However, relying on this is discouraged; explicitly convert using :func:`int`
892892
instead.
893893

894+
.. _iterator-types:
895+
894896
.. _typeiter:
895897

896-
Iterator Types
897-
==============
898+
Iteration-related types
899+
=======================
898900

899901
.. index::
900902
single: iterator protocol
@@ -907,6 +909,9 @@ using two distinct methods; these are used to allow user-defined classes to
907909
support iteration. Sequences, described below in more detail, always support
908910
the iteration methods.
909911

912+
Iterables
913+
---------
914+
910915
One method needs to be defined for container objects to provide :term:`iterable`
911916
support:
912917

@@ -923,10 +928,14 @@ support:
923928
:c:member:`~PyTypeObject.tp_iter` slot of the type structure for Python
924929
objects in the Python/C API.
925930

931+
.. _stdtypes-iterators:
932+
933+
Iterators
934+
---------
935+
926936
The iterator objects themselves are required to support the following two
927937
methods, which together form the :dfn:`iterator protocol`:
928938

929-
930939
.. method:: iterator.__iter__()
931940

932941
Return the :term:`iterator` object itself. This is required to allow both
@@ -955,16 +964,278 @@ Implementations that do not obey this property are deemed broken.
955964

956965
.. _generator-types:
957966

958-
Generator Types
967+
Generator types
959968
---------------
960969

961-
Python's :term:`generator`\s provide a convenient way to implement the iterator
962-
protocol. If a container object's :meth:`~object.__iter__` method is implemented as a
963-
generator, it will automatically return an iterator object (technically, a
964-
generator object) supplying the :meth:`~iterator.__iter__` and :meth:`~generator.__next__`
965-
methods.
966-
More information about generators can be found in :ref:`the documentation for
967-
the yield expression <yieldexpr>`.
970+
Python's :term:`generators <generator>` -- or more precisely,
971+
:term:`generator functions <generator function>` and
972+
:term:`generator iterators <generator iterator>` -- provide a convenient way
973+
to implement the iterator protocol.
974+
975+
A function that contains one or more :ref:`yield expressions <yieldexpr>`
976+
is a :term:`generator function`.
977+
For example::
978+
979+
>>> def count_to_three():
980+
... yield 0
981+
... yield 1
982+
... yield 2
983+
... yield 3
984+
985+
Generator functions behave as regular
986+
:ref:`user-defined functions <user-defined-funcs>`
987+
(for example, they have the same attributes), except that calling a generator
988+
function returns a :ref:`generator iterator <generator-methods>`::
989+
990+
>>> count_to_three()
991+
<generator object count_to_three at 0x7f33a2305000>
992+
993+
Iterating a generator iterator executes code of the underlying
994+
generator function, producing each :keyword:`yield`\ed value in turn::
995+
996+
>>> for number in count_to_three():
997+
... print(number)
998+
0
999+
1
1000+
2
1001+
3
1002+
1003+
>>> list(count_to_three())
1004+
[0, 1, 2, 3]
1005+
1006+
One common use for generator functions is implementing the
1007+
:meth:`~object.__iter__` method of custom iterable objects.
1008+
For example::
1009+
1010+
>>> class CardDeck:
1011+
... def __iter__(self):
1012+
... yield 'three of clubs'
1013+
... yield 'ace of hearts'
1014+
1015+
>>> list(CardDeck())
1016+
['three of clubs', 'ace of hearts']
1017+
1018+
1019+
.. index:: pair: object; generator
1020+
.. _generator-methods:
1021+
1022+
Generator iterators
1023+
^^^^^^^^^^^^^^^^^^^
1024+
1025+
Generator iterators implement the
1026+
:ref:`iterator protocol <stdtypes-iterators>`.
1027+
Iterating them drives execution of the underlying generator function.
1028+
1029+
.. index:: pair: exception; StopIteration
1030+
1031+
.. method:: generator.__next__()
1032+
1033+
Starts the execution of a generator function or resumes it at the
1034+
:ref:`yield expression <yieldexpr>` where the function is currently suspended.
1035+
When a generator function is resumed with a :meth:`~generator.__next__`
1036+
method, the current yield expression always evaluates to :const:`None`.
1037+
The execution then continues to the next yield expression, where the
1038+
generator is suspended again, and the value of the expression after the
1039+
:keyword:`yield` keyword is returned to :meth:`~generator.__next__`'s
1040+
caller.
1041+
If the generator exits without yielding another value,
1042+
:meth:`~generator.__next__` raises a :exc:`StopIteration` exception,
1043+
signalling that iteration has completed.
1044+
1045+
This method is normally called implicitly, for example by a :keyword:`for`
1046+
loop, or by the built-in :func:`next` function.
1047+
1048+
Generator iterators have a few more methods than generic iterators, which
1049+
can be used to control the execution of the underlying generator function:
1050+
1051+
.. method:: generator.send(value)
1052+
1053+
"Sends" a value into the generator function: the *value* argument becomes
1054+
the result of the current yield expression.
1055+
1056+
Otherwise, this method behaves like :meth:`~generator.__next__`: it resumes
1057+
the underlying function and either returns the next yielded value or raises
1058+
:exc:`StopIteration`.
1059+
1060+
When :meth:`send` is called to start the generator, it must be called
1061+
with :const:`None` as the argument, because there is no current yield
1062+
expression that could receive the value.
1063+
1064+
1065+
.. method:: generator.throw(value)
1066+
generator.throw(type[, value[, traceback]])
1067+
1068+
Raises an exception at the point where the generator is currently suspended.
1069+
1070+
Otherwise, this method behaves like :meth:`~generator.__next__`: it resumes
1071+
the underlying function and either returns the next yielded value or raises
1072+
:exc:`StopIteration`.
1073+
If the generator function does not catch the passed-in exception, or
1074+
raises a different exception, then that exception propagates to the caller.
1075+
1076+
When :meth:`throw` is called to start the generator, the generator
1077+
immediately exits (that is, subsequent calls to :meth:`~generator.__next__`
1078+
will raise :exc:`StopIteration`) and the thrown exception is propagated to
1079+
:meth:`throw`'s caller.
1080+
1081+
In typical use, this is called with a single argument, an exception instance,
1082+
similar to the way the :keyword:`raise` keyword is used.
1083+
1084+
For backwards compatibility, however, the second signature is
1085+
supported, following a convention from older versions of Python.
1086+
The *type* argument should be an exception class, and *value*
1087+
should be an exception instance. If the *value* is not provided, the
1088+
*type* constructor is called to get an instance. If *traceback*
1089+
is provided, it is set on the exception, otherwise any existing
1090+
:attr:`~BaseException.__traceback__` attribute stored in *value* may
1091+
be cleared.
1092+
1093+
.. versionchanged:: 3.12
1094+
1095+
The second signature \(type\[, value\[, traceback\]\]\) is deprecated and
1096+
may be removed in a future version of Python.
1097+
1098+
.. index:: pair: exception; GeneratorExit
1099+
1100+
.. method:: generator.close()
1101+
1102+
Raises a :exc:`GeneratorExit` exception at the point where the generator
1103+
function is currently suspended (equivalent to calling ``throw(GeneratorExit)``).
1104+
1105+
If the generator function has already exited (due to an exception or
1106+
normal return), or raises :exc:`GeneratorExit` (by not catching the
1107+
exception), :meth:`close` returns :const:`None`.
1108+
If the generator yields a value, a :exc:`RuntimeError` is raised.
1109+
If the generator raises any other exception, it is propagated to the caller.
1110+
If a generator returns a value upon being closed, that value is returned
1111+
by :meth:`close`.
1112+
1113+
When a generator iterator is garbage collected before it has exited,
1114+
:meth:`~generator.close` is called automatically.
1115+
1116+
.. versionchanged:: 3.13
1117+
1118+
If a generator returns a value upon being closed, the value is returned
1119+
by :meth:`close`.
1120+
Previously, it returned ``None``.
1121+
1122+
1123+
Calling any of the generator methods (:meth:`~generator.__next__`,
1124+
:meth:`~generator.send`, :meth:`~generator.throw`, :meth:`~generator.close`)
1125+
while one of these methods is already executing
1126+
raises a :exc:`ValueError` exception.
1127+
1128+
1129+
.. index:: pair: object; asynchronous-generator
1130+
.. _asynchronous-generator-methods:
1131+
1132+
Asynchronous generator iterators
1133+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1134+
1135+
This subsection describes the methods of an asynchronous generator iterator,
1136+
which are used to control the execution of an asynchronous generator function.
1137+
1138+
1139+
.. index:: pair: exception; StopAsyncIteration
1140+
1141+
.. method:: agen.__anext__()
1142+
:async:
1143+
1144+
Returns an :term:`awaitable` which when run starts to execute the
1145+
asynchronous generator function or resumes it at the
1146+
:ref:`yield expression <yieldexpr>` where the function is currently suspended.
1147+
When an asynchronous generator function is resumed with an
1148+
:meth:`~agen.__anext__` method, the current yield expression always
1149+
evaluates to :const:`None` in the returned awaitable, which when run will
1150+
continue to the next yield expression.
1151+
The value of the expression after the :keyword:`yield` keyword is the value
1152+
of the :exc:`StopIteration` exception raised by the completing coroutine.
1153+
If the asynchronous generator exits without yielding another value, the
1154+
awaitable instead raises a :exc:`StopAsyncIteration` exception,
1155+
signalling that the asynchronous iteration has completed.
1156+
1157+
This method is normally called implicitly by an :keyword:`async for` loop,
1158+
or by the built-in :func:`anext` function.
1159+
1160+
1161+
Asynchronous generator-iterators have a few more methods than generic
1162+
asynchronous iterators, which can be used to control the execution of
1163+
the underlying generator function:
1164+
1165+
.. method:: agen.asend(value)
1166+
:async:
1167+
1168+
Returns an awaitable which, when run, "sends" a value into the underlying
1169+
asynchronous generator function: the *value* argument becomes
1170+
the result of the current yield expression.
1171+
1172+
Otherwise, this method behaves like :meth:`~agen.__anext__`: when the
1173+
returned awaitable runs, it resumes the underlying function and either
1174+
returns the next yielded value as the value of the raised
1175+
:exc:`StopIteration`, or raises :exc:`StopAsyncIteration`.
1176+
1177+
When :meth:`asend` is called to start the asynchronous
1178+
generator, it must be called with :const:`None` as the argument,
1179+
because there is no yield expression that could receive the value.
1180+
1181+
1182+
.. method:: agen.athrow(value)
1183+
agen.athrow(type[, value[, traceback]])
1184+
:async:
1185+
1186+
Returns an awaitable that, when run, raises an exception at the point where
1187+
the underlying asynchronous generator function is currently suspended.
1188+
1189+
Otherwise, this method behaves like :meth:`~agen.__anext__`: when the
1190+
returned awaitable runs, it resumes the underlying function (with an
1191+
exception raised) and either returns the next yielded value as the value of
1192+
the raised :exc:`StopIteration`, or raises :exc:`StopAsyncIteration`.
1193+
If the underlying function does not catch the passed-in exception, or
1194+
raises a different exception, then when the awaitable is run, that
1195+
exception propagates to the caller of the awaitable.
1196+
1197+
When :meth:`~agen.athrow` is called to start the generator, the generator
1198+
exits when the awaitable runs (that is, subsequent results from
1199+
:meth:`~agen.__anext__` will raise :exc:`StopAsyncIteration` when run)
1200+
and the thrown exception is propagated to the awaitable's caller.
1201+
1202+
In typical use, this is called with a single argument, an exception instance,
1203+
similar to the way the :keyword:`raise` keyword is used.
1204+
1205+
For backwards compatibility, however, the second signature is
1206+
supported.
1207+
An exception instance is created from three arguments in the same way as in
1208+
:meth:`generator.throw`.
1209+
1210+
.. versionchanged:: 3.12
1211+
1212+
The second signature \(type\[, value\[, traceback\]\]\) is deprecated and
1213+
may be removed in a future version of Python.
1214+
1215+
1216+
.. index:: pair: exception; GeneratorExit
1217+
1218+
.. method:: agen.aclose()
1219+
:async:
1220+
1221+
Returns an awaitable that when run will throw a :exc:`GeneratorExit` into
1222+
the underlying asynchronous generator function at the point where it is
1223+
currently suspended (equivalent to calling ``athrow(GeneratorExit)``).
1224+
1225+
If the asynchronous generator function then exits gracefully, is already
1226+
closed, or raises :exc:`GeneratorExit` (by not catching the exception),
1227+
then the returned awaitable will raise a :exc:`StopIteration` exception.
1228+
Any further awaitables returned by subsequent calls to the asynchronous
1229+
generator will raise a :exc:`StopAsyncIteration` exception.
1230+
1231+
If the asynchronous generator yields a value, a :exc:`RuntimeError` is
1232+
raised by the awaitable.
1233+
If the asynchronous generator raises any other exception, that exception
1234+
is propagated to the caller of the awaitable.
1235+
1236+
If the asynchronous generator has already exited due to an exception or
1237+
normal exit, then further calls to :meth:`aclose` will return an awaitable
1238+
that does nothing.
9681239

9691240

9701241
.. _typesseq:

0 commit comments

Comments
 (0)