Skip to content

Lower-level TaskGroup API #577

Closed Answered by agronholm
davidbrochart asked this question in Q&A
Discussion options

You must be logged in to vote

It may be kosher in simple situations (this one qualifies), but unwrapping aexit calls isn't exactly trivial. Just look at the implementation of [async]contextmanager.

In nontrivial cases I just use an async exit stack:

async def __aenter__(self):
    async with AsyncExitStack() as exit_stack:
        self._nursery = await exit_stack.enter_async_context(open_nursery())
        self._exit_stack = exit_stack.pop_all()

async def __aexit__(self, exc_type, exc_value, exc_tb):
    return await self._exit_stack.__aexit__(exc_type, exc_value, exc_tb)

What's nice about this approach is that if bad things happen in __aenter__() already, it still closes all the resources that have already been pu…

Replies: 5 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@agronholm
Comment options

Answer selected by davidbrochart
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
5 participants