Skip to content
Closed
Changes from all commits
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
18 changes: 14 additions & 4 deletions docs/rules.rst
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,20 @@ _`ASYNC118` : cancelled-class-saved
Don't assign the value of :func:`anyio.get_cancelled_exc_class` to a variable, since that breaks linter checks and multi-backend programs.

_`ASYNC119` : yield-in-cm-in-async-gen
``yield`` in context manager in async generator is unsafe, the cleanup may be delayed until ``await`` is no longer allowed.
We strongly encourage you to read :pep:`533` and use `async with aclosing(...) <https://docs.python.org/3/library/contextlib.html#contextlib.aclosing>`_.
:func:`trio.as_safe_channel` has been designed to be a drop-in replacement to transform
any unsafe async generator into a context manager that uses :ref:`streams <channel_stream_queue>` and safely runs the generator in a background task.
This rule checks for ``yield`` inside either ``with`` or ``async with`` in an async generator.
Leaving an ``async for`` loop early can leave the generator suspended inside the context manager.
For example, a file opened by a synchronous ``with`` can remain open after the caller breaks out of the loop.

Deferred cleanup can run outside the caller's context.
:func:`asyncio.run` and :func:`trio.run` finalize still-open async generators at shutdown.
Trio's implicit finalization runs with cancellation already active, so a checkpoint in the cleanup can raise :exc:`trio.Cancelled`.
See :pep:`533` and `Trio's notes on async generator finalization <https://trio.readthedocs.io/en/stable/reference-core.html#finalization>`_.

If the context manager only protects work needed to produce a value, leave it before yielding the value.
If you control the caller, wrap the iteration in :func:`contextlib.aclosing` (Python 3.10+) to close the generator in the caller's context when leaving early.
To expose a managed resource, use :func:`contextlib.asynccontextmanager`.
In Trio, :func:`trio.as_safe_channel` can run the generator in a background task and expose a receive channel through an async context manager.
See :ref:`ASYNC101 <ASYNC101>` for the separate restrictions on yielding inside a nursery or cancel scope.

_`ASYNC120` : await-in-except
Dangerous :ref:`checkpoint` inside an ``except`` block.
Expand Down
Loading