-
-
Notifications
You must be signed in to change notification settings - Fork 354
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add @background_with_channel
#3197
Open
jakkdl
wants to merge
27
commits into
python-trio:main
Choose a base branch
from
jakkdl:background_with_channel
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
317cb1c
Update _channel.py
Zac-HD 1a7714e
Merge remote-tracking branch 'zachd/async-generator-decorator' into b…
jakkdl b0b8b02
add tests, and some types
jakkdl 8584cff
Fix race condition
A5rocks 274755f
fix race condition + exception eating, make sure we always clean up, …
jakkdl 428dd4b
Merge branch 'main' into background_with_channel
jakkdl 7542973
restore prev default, fix codecov
jakkdl 86d3b0f
Update src/trio/_channel.py
jakkdl 2d11ea2
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] a5734f6
clean up comments, add some others, and remove unnecessary ait/agen d…
jakkdl 0b461d2
add newsfragment, docs. building docs is failing locally on AbstractA…
jakkdl b86eb54
fix minor docstring errors
jakkdl 7936fd2
Merge branch 'main' into background_with_channel
jakkdl 6e71d4e
Merge remote-tracking branch 'origin/main' into background_with_channel
jakkdl 1670674
docs&newsfragment fixes after review, remove aclosing
jakkdl 7acf3a0
Fix sphinx type hint resolution
TeamSpen210 69a95dc
Merge remote-tracking branch 'origin/main' into background_with_channel
jakkdl efe2d00
fix coverage. Would be great to have tox+coverage now... :eyes:
jakkdl f78f641
fix interleaved execution on non-0 buffer size
jakkdl 5bfb0c5
specify strict_exception_groups, clarify drop-in replacement status
jakkdl 54800e2
Apply suggestions from code review
jakkdl 0e34b85
codecov, fix tests after functionality change
jakkdl 1b8ce0a
codecov
jakkdl ec61a1f
Merge branch 'main' into background_with_channel
jakkdl 9f8a2ab
:100: plx
jakkdl bfa981c
okay now actually 100% coverage
jakkdl 26ed1c6
do everything but unwrapping the exception from inside the group
jakkdl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Add :func:`@trio.background_with_channel <trio.background_with_channel>`, a wrapper that can be used to make async generators safe. This will be the suggested fix for `ASYNC900 <https://flake8-async.readthedocs.io/en/latest/rules.html#async900>`_. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,10 @@ | ||
from __future__ import annotations | ||
|
||
import sys | ||
from collections import OrderedDict, deque | ||
from collections.abc import AsyncGenerator, Callable # noqa: TC003 # Needed for Sphinx | ||
from contextlib import AbstractAsyncContextManager, asynccontextmanager | ||
from functools import wraps | ||
from math import inf | ||
from typing import ( | ||
TYPE_CHECKING, | ||
|
@@ -19,7 +23,17 @@ | |
if TYPE_CHECKING: | ||
from types import TracebackType | ||
|
||
from typing_extensions import Self | ||
from typing_extensions import ParamSpec, Self | ||
|
||
P = ParamSpec("P") | ||
elif "sphinx" in sys.modules: | ||
# P needs to exist for Sphinx to parse the type hints successfully. | ||
try: | ||
from typing_extensions import ParamSpec | ||
except ImportError: | ||
P = ... # This is valid in Callable, though not correct | ||
else: | ||
P = ParamSpec("P") | ||
|
||
|
||
def _open_memory_channel( | ||
|
@@ -440,3 +454,122 @@ async def aclose(self) -> None: | |
See `MemoryReceiveChannel.close`.""" | ||
self.close() | ||
await trio.lowlevel.checkpoint() | ||
|
||
|
||
class RecvChanWrapper(ReceiveChannel[T]): | ||
def __init__( | ||
self, recv_chan: MemoryReceiveChannel[T], send_semaphore: trio.Semaphore | ||
) -> None: | ||
self.recv_chan = recv_chan | ||
self.send_semaphore = send_semaphore | ||
|
||
# TODO: should this allow clones? We'd signal that by inheriting from | ||
# MemoryReceiveChannel. | ||
|
||
async def receive(self) -> T: | ||
self.send_semaphore.release() | ||
return await self.recv_chan.receive() | ||
|
||
async def aclose(self) -> None: | ||
await self.recv_chan.aclose() | ||
|
||
def __enter__(self) -> Self: | ||
return self | ||
|
||
def __exit__( | ||
self, | ||
exc_type: type[BaseException] | None, | ||
exc_value: BaseException | None, | ||
traceback: TracebackType | None, | ||
) -> None: | ||
self.recv_chan.close() | ||
|
||
|
||
def background_with_channel( | ||
fn: Callable[P, AsyncGenerator[T, None]], | ||
) -> Callable[P, AbstractAsyncContextManager[ReceiveChannel[T]]]: | ||
"""Decorate an async generator function to make it cancellation-safe. | ||
|
||
This is mostly a drop-in replacement, except for the fact that it will | ||
wrap errors in exception groups due to the internal nursery. Although when | ||
using it without a buffer it should be exceedingly rare to get multiple | ||
exceptions. | ||
|
||
The ``yield`` keyword offers a very convenient way to write iterators... | ||
which makes it really unfortunate that async generators are so difficult | ||
to call correctly. Yielding from the inside of a cancel scope or a nursery | ||
to the outside `violates structured concurrency <https://xkcd.com/292/>`_ | ||
with consequences explained in :pep:`789`. Even then, resource cleanup | ||
errors remain common (:pep:`533`) unless you wrap every call in | ||
:func:`~contextlib.aclosing`. | ||
|
||
This decorator gives you the best of both worlds: with careful exception | ||
handling and a background task we preserve structured concurrency by | ||
offering only the safe interface, and you can still write your iterables | ||
with the convenience of ``yield``. For example:: | ||
|
||
@background_with_channel | ||
async def my_async_iterable(arg, *, kwarg=True): | ||
while ...: | ||
item = await ... | ||
yield item | ||
|
||
async with my_async_iterable(...) as recv_chan: | ||
async for item in recv_chan: | ||
... | ||
|
||
While the combined async-with-async-for can be inconvenient at first, | ||
the context manager is indispensable for both correctness and for prompt | ||
cleanup of resources. | ||
|
||
If you specify ``max_buffer_size>0`` the async generator will run concurrently | ||
with your iterator, until the buffer is full. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This isn't applicable anymore? |
||
""" | ||
jakkdl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
# Perhaps a future PEP will adopt `async with for` syntax, like | ||
# https://coconut.readthedocs.io/en/master/DOCS.html#async-with-for | ||
|
||
@asynccontextmanager | ||
@wraps(fn) | ||
async def context_manager( | ||
*args: P.args, **kwargs: P.kwargs | ||
) -> AsyncGenerator[trio._channel.RecvChanWrapper[T], None]: | ||
send_chan, recv_chan = trio.open_memory_channel[T](0) | ||
async with trio.open_nursery(strict_exception_groups=True) as nursery: | ||
agen = fn(*args, **kwargs) | ||
send_semaphore = trio.Semaphore(0) | ||
# `nursery.start` to make sure that we will clean up send_chan & agen | ||
# If this errors we don't close `recv_chan`, but the caller | ||
# never gets access to it, so that's not a problem. | ||
await nursery.start(_move_elems_to_channel, agen, send_chan, send_semaphore) | ||
# `async with recv_chan` could eat exceptions, so use sync cm | ||
with RecvChanWrapper(recv_chan, send_semaphore) as wrapped_recv_chan: | ||
yield wrapped_recv_chan | ||
# User has exited context manager, cancel to immediately close the | ||
# abandoned generator if it's still alive. | ||
nursery.cancel_scope.cancel() | ||
|
||
async def _move_elems_to_channel( | ||
agen: AsyncGenerator[T, None], | ||
send_chan: trio.MemorySendChannel[T], | ||
send_semaphore: trio.Semaphore, | ||
task_status: trio.TaskStatus, | ||
) -> None: | ||
# `async with send_chan` will eat exceptions, | ||
# see https://github.com/python-trio/trio/issues/1559 | ||
with send_chan: | ||
try: | ||
task_status.started() | ||
while True: | ||
# wait for receiver to call next on the aiter | ||
await send_semaphore.acquire() | ||
try: | ||
value = await agen.__anext__() | ||
except StopAsyncIteration: | ||
return | ||
# Send the value to the channel | ||
await send_chan.send(value) | ||
finally: | ||
# replace try-finally with contextlib.aclosing once python39 is dropped | ||
await agen.aclose() | ||
|
||
return context_manager |
Zac-HD marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sphinx does have some issues with auto-documenting annotations, yep. Should be better once we're in the brave new world of 3.14+
annotationslib
... in another 4.5 years. Ah well.