diff --git a/docs/rules.rst b/docs/rules.rst index 2082bcc..84c142f 100644 --- a/docs/rules.rst +++ b/docs/rules.rst @@ -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(...) `_. - :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 ` 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 `_. + + 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 ` for the separate restrictions on yielding inside a nursery or cancel scope. _`ASYNC120` : await-in-except Dangerous :ref:`checkpoint` inside an ``except`` block.