

This is treated the same as if one of the tasks failed: (so _aexit_() is called with an exception set),

If the body of the async with statement exits with an exception Is re-raised instead of ExceptionGroup or BaseExceptionGroup. The task group still cancels the remaining tasks and waits for them,īut then the initial KeyboardInterrupt or SystemExit If any task fails with KeyboardInterrupt or SystemExit, Two base exceptions are treated specially: Once all tasks have finished, if any tasks have failed The resulting asyncio.CancelledError will interrupt an await,īut it will not bubble out of the containing async with statement. The task directly containing the async with statement is also cancelled. (i.e., _aexit_() hasn’t been called yet), No further tasks can then be added to the group.Īt this point, if the body of the async with statement is still active The remaining tasks in the group are cancelled. With an exception other than asyncio.CancelledError, The first time any of the tasks belonging to the group fails Once the last task has finished and the async with block is exited, (for example, by passing tg into one of the coroutinesĪnd calling tg.create_task() in that coroutine). While waiting, new tasks may still be added to the group The async with statement will wait for all tasks in the group to finish. )) print ( "Both tasks have completed now." ) Tasks can be added to the group using create_task().Īll tasks are awaited when the context manager exits.Īsync def main (): async with asyncio.

Task groups combine a task creation API with a convenientĪnd reliable way to wait for all tasks in the group to finish. The asyncio components that enable structured concurrency, likeĪre implemented using cancellation internally and might misbehave ifĪ coroutine swallows asyncio.CancelledError. Most code can safely ignore asyncio.CancelledError. Is explicitly caught, it should generally be propagated whenĬlean-up is complete. It is recommended that coroutines use try/finally blocks to robustly When a task is cancelled, asyncio.CancelledError will be raised Tasks can easily and safely be cancelled. Changed in version 3.11: Added the context parameter.
