Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Update section about iterating agen after running event loop
  • Loading branch information
sergey-miryanov committed Nov 26, 2025
commit a70038a976e364adf7dd8ae966c5d9ab7b536f83
29 changes: 22 additions & 7 deletions Doc/library/asyncio-dev.rst
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@
an :term:`asynchronous generator iterator` that is returned by an
:term:`asynchronous generator` function.


Manually close the generator
----------------------------

Expand Down Expand Up @@ -284,22 +285,36 @@

asyncio.run(func())


Comment thread
sergey-miryanov marked this conversation as resolved.
Only create a generator when a loop is already running
------------------------------------------------------

As said above, if an asynchronous generator is not resumed before it is
finalized, then any finalization procedures will be delayed. The event loop
handles this situation and doing its best to call the async generator-iterator's
:meth:`~agen.aclose` method at the proper moment, thus allowing any pending
:keyword:`!finally` clauses to run.

Then it is recomended to create async generators only after the event loop
It is recommended to create asynchronous generators only after the event loop
has already been created.

To ensure that asynchronous generators close reliably, the event loop uses the
:func:`sys.set_asyncgen_hooks` function to register callback functions. These
callbacks update the list of running asynchronous generators to keep it in a
consistent state.

When the :meth:`loop.shutdown_asyncgens() <asyncio.loop.shutdown_asyncgens>`
function is called, the running generators are stopped gracefully, and the
list is cleared.

The asynchronous generator calls the corresponding system hook when on the
first iteration. At the same time, the generator remembers that the hook was
called and don't call it twice.

So, if the iteration begins before the event loop is created, the event loop
will not be able to add it to its list of active generators because the hooks
will be set after the generator tries to call it. Consequently, the event loop
will not be able to terminate the generator if necessary.


Avoid iterating and closing the same generator concurrently
-----------------------------------------------------------

Async generators may to be reentered while another

Check warning on line 317 in Doc/library/asyncio-dev.rst

View workflow job for this annotation

GitHub Actions / Docs / Docs

py:meth reference target not found: agen.anext [ref.meth]
:meth:`~agen.anext`/:meth:`~agen.athrow`/:meth:`~agen.aclose` call is in
progress. This may lead to an inconsistent state of the async generator
and can cause errors.
Expand Down
Loading