Skip to content

Commit a70038a

Browse files
Update section about iterating agen after running event loop
1 parent 3556aef commit a70038a

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

Doc/library/asyncio-dev.rst

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,7 @@ By :term:`asynchronous generator` in this section we will mean
257257
an :term:`asynchronous generator iterator` that is returned by an
258258
:term:`asynchronous generator` function.
259259

260+
260261
Manually close the generator
261262
----------------------------
262263

@@ -284,18 +285,32 @@ manager::
284285

285286
asyncio.run(func())
286287

288+
287289
Only create a generator when a loop is already running
288290
------------------------------------------------------
289291

290-
As said above, if an asynchronous generator is not resumed before it is
291-
finalized, then any finalization procedures will be delayed. The event loop
292-
handles this situation and doing its best to call the async generator-iterator's
293-
:meth:`~agen.aclose` method at the proper moment, thus allowing any pending
294-
:keyword:`!finally` clauses to run.
295-
296-
Then it is recomended to create async generators only after the event loop
292+
It is recommended to create asynchronous generators only after the event loop
297293
has already been created.
298294

295+
To ensure that asynchronous generators close reliably, the event loop uses the
296+
:func:`sys.set_asyncgen_hooks` function to register callback functions. These
297+
callbacks update the list of running asynchronous generators to keep it in a
298+
consistent state.
299+
300+
When the :meth:`loop.shutdown_asyncgens() <asyncio.loop.shutdown_asyncgens>`
301+
function is called, the running generators are stopped gracefully, and the
302+
list is cleared.
303+
304+
The asynchronous generator calls the corresponding system hook when on the
305+
first iteration. At the same time, the generator remembers that the hook was
306+
called and don't call it twice.
307+
308+
So, if the iteration begins before the event loop is created, the event loop
309+
will not be able to add it to its list of active generators because the hooks
310+
will be set after the generator tries to call it. Consequently, the event loop
311+
will not be able to terminate the generator if necessary.
312+
313+
299314
Avoid iterating and closing the same generator concurrently
300315
-----------------------------------------------------------
301316

0 commit comments

Comments
 (0)