@@ -926,6 +926,8 @@ support:
926926 :c:member: `~PyTypeObject.tp_iter ` slot of the type structure for Python
927927 objects in the Python/C API.
928928
929+ .. _stdtypes-iterators :
930+
929931Iterators
930932---------
931933
@@ -963,8 +965,10 @@ Implementations that do not obey this property are deemed broken.
963965Generator Types
964966---------------
965967
966- Python's :term: `generators <generator> ` provide a convenient way to implement
967- the iterator protocol.
968+ Python's :term: `generators <generator> ` -- or more precisely,
969+ :term: `generator functions <generator function> ` and
970+ :term: `generator iterators <generator iterator> ` -- provide a convenient way
971+ to implement the iterator protocol.
968972
969973A function that contains one or more :ref: `yield expressions <yieldexpr >`
970974is a :term: `generator function `.
@@ -976,9 +980,10 @@ For example::
976980 ... yield 2
977981 ... yield 3
978982
979- Generator functions behave as regular :ref: `user-defined functions <user-defined-funcs >`
980- (for example, they have the same attributes).
981- Calling a generator function returns a :term: `generator iterator `::
983+ Generator functions behave as regular
984+ :ref: `user-defined functions <user-defined-funcs >`
985+ (for example, they have the same attributes), except that calling a generator
986+ function returns a :ref: `generator iterator <generator-methods >`::
982987
983988 >>> count_to_three()
984989 <generator object count_to_three at 0x7f33a2305000>
@@ -993,8 +998,12 @@ generator function, producing each :keyword:`yield`\ed value in turn::
993998 2
994999 3
9951000
996- The :meth: `~object.__iter__ ` method of custom iterable objects may be
997- implemented directly as a generator function. For example::
1001+ >>> list(count_to_three())
1002+ [0, 1, 2, 3]
1003+
1004+ One common use for generator functions is implementing the
1005+ :meth: `~object.__iter__ ` method of custom iterable objects.
1006+ For example::
9981007
9991008 >>> class CardDeck:
10001009 ... def __iter__(self):
@@ -1011,56 +1020,64 @@ implemented directly as a generator function. For example::
10111020Generator iterators
10121021^^^^^^^^^^^^^^^^^^^
10131022
1014- Generator iterators implement the iterator protocol.
1023+ Generator iterators implement the
1024+ :ref: `iterator protocol <stdtypes-iterators >`.
10151025Iterating them drives execution of the underlying generator function.
10161026
10171027.. index :: pair: exception; StopIteration
10181028
10191029.. method :: generator.__next__()
10201030
1021- Starts the execution of a generator function or resumes it at the last
1022- executed yield expression. When a generator function is resumed with a
1023- :meth: `~generator.__next__ ` method, the current yield expression always
1024- evaluates to :const: `None `. The execution then continues to the next yield
1025- expression, where the generator is suspended again, and the value of the
1026- :token: `~python-grammar:yield_list ` is returned to :meth: `__next__ `'s
1027- caller. If the generator exits without yielding another value, a
1028- :exc: `StopIteration ` exception is raised.
1031+ Starts the execution of a generator function or resumes it at the
1032+ :ref: `yield expression <yieldexpr >` where the function is currently suspended.
1033+ When a generator function is resumed with a :meth: `~generator.__next__ `
1034+ method, the current yield expression always evaluates to :const: `None `.
1035+ The execution then continues to the next yield expression, where the
1036+ generator is suspended again, and the value of the expression after the
1037+ :keyword: `yield ` keyword is returned to :meth: `~generator.__next__ `'s
1038+ caller.
1039+ If the generator exits without yielding another value,
1040+ :meth: `~generator.__next__ ` raises a :exc: `StopIteration ` exception,
1041+ signalling that iteration has completed.
10291042
1030- This method is normally called implicitly, e.g. by a :keyword: `for ` loop, or
1031- by the built-in :func: `next ` function.
1043+ This method is normally called implicitly, for example by a :keyword: `for `
1044+ loop, or by the built-in :func: `next ` function.
10321045
1033- Generator iterators have a few more functions than generic iterators.
1046+ Generator iterators have a few more methods than generic iterators, which
1047+ can be used to control the execution of the underlying generator function:
10341048
1035- This subsection describes the methods of a generator iterator. They can
1036- be used to control the execution of a generator function.
1037-
1038- Note that calling any of the generator methods below when the generator
1039- is already executing raises a :exc: `ValueError ` exception.
1049+ .. method :: generator.send(value)
10401050
1051+ "Sends" a value into the generator function: the *value * argument becomes
1052+ the result of the current yield expression.
10411053
1042- .. method :: generator.send(value)
1054+ Otherwise, this method behaves like :meth: `~generator.__next__ `: it resumes
1055+ the underlying function and either returns the next yielded value or raises
1056+ :exc: `StopIteration `.
10431057
1044- Resumes the execution and "sends" a value into the generator function. The
1045- *value * argument becomes the result of the current yield expression. The
1046- :meth: `send ` method returns the next value yielded by the generator, or
1047- raises :exc: `StopIteration ` if the generator exits without yielding another
1048- value. When :meth: `send ` is called to start the generator, it must be called
1049- with :const: `None ` as the argument, because there is no yield expression that
1050- could receive the value.
1058+ When :meth: `send ` is called to start the generator, it must be called
1059+ with :const: `None ` as the argument, because there is no current yield
1060+ expression that could receive the value.
10511061
10521062
10531063.. method :: generator.throw(value)
10541064 generator.throw(type[, value[, traceback]])
10551065
1056- Raises an exception at the point where the generator was paused,
1057- and returns the next value yielded by the generator function. If the generator
1058- exits without yielding another value, a :exc: `StopIteration ` exception is
1059- raised. If the generator function does not catch the passed-in exception, or
1066+ Raises an exception at the point where the generator is currently suspended.
1067+
1068+ Otherwise, this method behaves like :meth: `~generator.__next__ `: it resumes
1069+ the underlying function and either returns the next yielded value or raises
1070+ :exc: `StopIteration `.
1071+ If the generator function does not catch the passed-in exception, or
10601072 raises a different exception, then that exception propagates to the caller.
10611073
1062- In typical use, this is called with a single exception instance similar to the
1063- way the :keyword: `raise ` keyword is used.
1074+ When :meth: `throw ` is called to start the generator, the generator
1075+ immediately exits (that is, subsequent calls to :meth: `~generator.__next__ `
1076+ will raise :exc: `StopIteration `) and the thrown exception is propagated to
1077+ :meth: `throw `'s caller.
1078+
1079+ In typical use, this is called with a single argument, an exception instance,
1080+ similar to the way the :keyword: `raise ` keyword is used.
10641081
10651082 For backwards compatibility, however, the second signature is
10661083 supported, following a convention from older versions of Python.
@@ -1078,68 +1095,81 @@ is already executing raises a :exc:`ValueError` exception.
10781095
10791096.. index :: pair: exception; GeneratorExit
10801097
1081-
10821098.. method :: generator.close()
10831099
10841100 Raises a :exc: `GeneratorExit ` exception at the point where the generator
1085- function was paused (equivalent to calling ``throw(GeneratorExit) ``).
1086- The exception is raised by the yield expression where the generator was paused.
1087- If the generator function catches the exception and returns a
1088- value, this value is returned from :meth: ` close `. If the generator function
1089- is already closed, or raises :exc: ` GeneratorExit ` (by not catching the
1090- exception), :meth: ` close ` returns :const: ` None `. If the generator yields a
1091- value, a :exc: ` RuntimeError ` is raised. If the generator raises any other
1092- exception, it is propagated to the caller. If the generator has already
1093- exited due to an exception or normal exit, :meth: ` close ` returns
1094- :const: ` None ` and has no other effect .
1101+ function is currently suspended (equivalent to calling ``throw(GeneratorExit) ``).
1102+
1103+ If the generator function has already exited (due to an exception or
1104+ normal return), or raises :exc: ` GeneratorExit ` (by not catching the
1105+ exception), :meth: ` close ` returns :const: ` None `.
1106+ If the generator yields a value, a :exc: ` RuntimeError ` is raised.
1107+ If the generator raises any other exception, it is propagated to the caller.
1108+
1109+ When a generator iterator is garbage collected before it has exited,
1110+ :meth: ` ~generator.close ` is called automatically .
10951111
10961112 .. versionchanged :: 3.13
10971113
10981114 If a generator returns a value upon being closed, the value is returned
10991115 by :meth: `close `.
1116+ Previously, the value was returned from :meth: `~generator.close `.
1117+
1118+
1119+ Calling any of the generator methods (:meth: `~generator.__next__ `,
1120+ :meth: `~generator.send `, :meth: `~generator.throw `, :meth: `~generator.close `)
1121+ while one of these methods is already executing
1122+ raises a :exc: `ValueError ` exception.
11001123
11011124
11021125.. index :: pair: object; asynchronous-generator
11031126.. _asynchronous-generator-methods :
11041127
1105- Asynchronous generator-iterator methods
1106- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1128+ Asynchronous generator-iterators
1129+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
11071130
11081131This subsection describes the methods of an asynchronous generator iterator,
1109- which are used to control the execution of a generator function.
1132+ which are used to control the execution of an asynchronous generator function.
11101133
11111134
11121135.. index :: pair: exception; StopAsyncIteration
11131136
11141137.. method :: agen.__anext__()
11151138 :async:
11161139
1117- Returns an awaitable which when run starts to execute the asynchronous
1118- generator or resumes it at the last executed yield expression. When an
1119- asynchronous generator function is resumed with an :meth: `~agen.__anext__ `
1120- method, the current yield expression always evaluates to :const: `None ` in the
1121- returned awaitable, which when run will continue to the next yield
1122- expression. The value of the :token: `~python-grammar:yield_list ` of the
1123- yield expression is the value of the :exc: `StopIteration ` exception raised by
1124- the completing coroutine. If the asynchronous generator exits without
1125- yielding another value, the awaitable instead raises a
1126- :exc: `StopAsyncIteration ` exception, signalling that the asynchronous
1127- iteration has completed.
1140+ Returns an :term: `awaitable ` which when run starts to execute the
1141+ asynchronous generator function or resumes it at the
1142+ :ref: `yield expression <yieldexpr >` where the function is currently suspended.
1143+ When an asynchronous generator function is resumed with an
1144+ :meth: `~agen.__anext__ ` method, the current yield expression always
1145+ evaluates to :const: `None ` in the returned awaitable, which when run will
1146+ continue to the next yield expression.
1147+ The value of the expression after the :keyword: `yield ` keyword is the value
1148+ of the :exc: `StopIteration ` exception raised by the completing coroutine.
1149+ If the asynchronous generator exits without yielding another value, the
1150+ awaitable instead raises a :exc: `StopAsyncIteration ` exception,
1151+ signalling that the asynchronous iteration has completed.
1152+
1153+ This method is normally called implicitly by a :keyword: `async for ` loop,
1154+ or by the built-in :func: `anext ` function.
11281155
1129- This method is normally called implicitly by a :keyword: `async for ` loop.
11301156
1157+ Asynchronous generator-iterators have a few more methods than generic
1158+ asynchronous iterators, which can be used to control the execution of
1159+ the underlying generator function:
11311160
11321161.. method :: agen.asend(value)
11331162 :async:
11341163
1135- Returns an awaitable which when run resumes the execution of the
1136- asynchronous generator. As with the :meth: `~generator.send ` method for a
1137- generator, this "sends" a value into the asynchronous generator function,
1138- and the *value * argument becomes the result of the current yield expression.
1139- The awaitable returned by the :meth: `asend ` method will return the next
1140- value yielded by the generator as the value of the raised
1141- :exc: `StopIteration `, or raises :exc: `StopAsyncIteration ` if the
1142- asynchronous generator exits without yielding another value. When
1164+ Returns an awaitable which, when run, "sends" a value into the underlying
1165+ asynchronous generator function: the *value * argument becomes
1166+ the result of the current yield expression.
1167+
1168+ Otherwise, this method behaves like :meth: `~agen.__anext__ `: when the
1169+ returned awaitable runs, it resumes the underlying function and either
1170+ returns the next yielded value as the value of the raised
1171+ :exc: `StopIteration `, or raises :exc: `StopAsyncIteration `.
1172+
11431173 :meth: `asend ` is called to start the asynchronous
11441174 generator, it must be called with :const: `None ` as the argument,
11451175 because there is no yield expression that could receive the value.
@@ -1149,34 +1179,80 @@ which are used to control the execution of a generator function.
11491179 agen.athrow(type[, value[, traceback]])
11501180 :async:
11511181
1152- Returns an awaitable that raises an exception of type ``type `` at the point
1153- where the asynchronous generator was paused, and returns the next value
1154- yielded by the generator function as the value of the raised
1155- :exc: `StopIteration ` exception. If the asynchronous generator exits
1156- without yielding another value, a :exc: `StopAsyncIteration ` exception is
1157- raised by the awaitable.
1158- If the generator function does not catch the passed-in exception, or
1159- raises a different exception, then when the awaitable is run that exception
1160- propagates to the caller of the awaitable.
1182+ Returns an awaitable that, when run, raises an exception at the point where
1183+ the underlying asynchronous generator function is currently suspended.
1184+
1185+ Otherwise, this method behaves like :meth: `~agen.__anext__ `: when the
1186+ returned awaitable runs, it resumes the underlying function (with an
1187+ exception raised) and either returns the next yielded value as the value of
1188+ the raised :exc: `StopIteration `, or raises :exc: `StopAsyncIteration `.
1189+ If the underlying function does not catch the passed-in exception, or
1190+ raises a different exception, then when the awaitable is run, that
1191+ exception propagates to the caller of the awaitable.
1192+
1193+ When :meth: `~agen.athrow ` is called to start the generator, the generator
1194+ exits when the awaitable runs (that is, subsequent results from
1195+ :meth: `~agen.__anext__ ` will raise :exc: `StopAsyncIteration ` when run)
1196+ and the thrown exception is propagated to the awaitable's caller.
1197+
1198+ In typical use, this is called with a single argument, an exception instance,
1199+ similar to the way the :keyword: `raise ` keyword is used.
1200+
1201+ For backwards compatibility, however, the second signature is
1202+ supported.
1203+ An exception instance is created from three arguments in the same way as in
1204+ :meth: `generator.__throw__ `
11611205
11621206 .. versionchanged :: 3.12
11631207
11641208 The second signature \( type\[ , value\[ , traceback\]\]\) is deprecated and
11651209 may be removed in a future version of Python.
11661210
1167- .. index :: pair: exception; GeneratorExit
11681211
1212+ TODO::: reword agen.aclose()
1213+
1214+ Raises a :exc: `GeneratorExit ` exception at the point where the generator
1215+ function is currently suspended (equivalent to calling ``throw(GeneratorExit) ``).
1216+
1217+ If the generator function has already exited (due to an exception or
1218+ normal return), or raises :exc: `GeneratorExit ` (by not catching the
1219+ exception), :meth: `close ` returns :const: `None `.
1220+ If the generator yields a value, a :exc: `RuntimeError ` is raised.
1221+ If the generator raises any other exception, it is propagated to the caller.
1222+
1223+ When a generator iterator is garbage collected before it has exited,
1224+ :meth: `~generator.close ` is called automatically.
1225+
1226+ .. versionchanged :: 3.13
1227+
1228+ If a generator returns a value upon being closed, the value is returned
1229+ by :meth: `close `.
1230+ Previously, the value was returned from :meth: `~generator.close `.
1231+
1232+
1233+ Calling any of the generator methods (:meth: `~generator.__next__ `,
1234+ :meth: `~generator.send `, :meth: `~generator.throw `, :meth: `~generator.close `)
1235+ while one of these methods is already executing
1236+ raises a :exc: `ValueError ` exception.
1237+
1238+
1239+
1240+ .. index :: pair: exception; GeneratorExit
11691241
11701242.. method :: agen.aclose()
11711243 :async:
11721244
11731245 Returns an awaitable that when run will throw a :exc: `GeneratorExit ` into
1174- the asynchronous generator function at the point where it was paused.
1246+ the underlying asynchronous generator function at the point where it is
1247+ currently suspended (equivalent to calling ``athrow(GeneratorExit) ``).
1248+
11751249 If the asynchronous generator function then exits gracefully, is already
11761250 closed, or raises :exc: `GeneratorExit ` (by not catching the exception),
11771251 then the returned awaitable will raise a :exc: `StopIteration ` exception.
11781252 Any further awaitables returned by subsequent calls to the asynchronous
1179- generator will raise a :exc: `StopAsyncIteration ` exception. If the
1253+ generator will raise a :exc: `StopAsyncIteration ` exception.
1254+
1255+ If the
11801256 asynchronous generator yields a value, a :exc: `RuntimeError ` is raised
11811257 by the awaitable. If the asynchronous generator raises any other exception,
11821258 it is propagated to the caller of the awaitable. If the asynchronous
0 commit comments