CKTIS / Python
asyncio.TaskGroup
Łączy zadania utworzone przez group.create_task w jeden zakres.
Wersja: Python 3.14; repository image, production runtime not attested
Składnia
async with asyncio.TaskGroup() as group:
task = group.create_task(coro)Łączy zadania utworzone przez group.create_task w jeden zakres.
Grupa może opuścić blok normalnie z anulowanym dzieckiem. Jego result() zgłosi wtedy CancelledError. Wyjście czeka na wszystkie dzieci, więc po sukcesie ich wyniki są gotowe. Pierwszy zwykły błąd anuluje rodzeństwo, po sprzątaniu błędy trafiają do ExceptionGroup lub BaseExceptionGroup. Samo anulowanie dziecka nie uruchamia tej reguły.
KeyboardInterrupt i SystemExit są zgłaszane osobno.
import asyncio
async def main():
async def fail():
raise ValueError("group")
try:
async with asyncio.TaskGroup() as tg:
sibling = tg.create_task(asyncio.Event().wait())
tg.create_task(fail())
except* ValueError as errors:
assert len(errors.exceptions) == 1
assert sibling.cancelled()
asyncio.run(main())
import asyncio
async def main():
async with asyncio.TaskGroup() as group:
child = group.create_task(asyncio.Event().wait())
child.cancel()
assert child.cancelled()
try:
child.result()
except asyncio.CancelledError:
pass
else:
raise AssertionError
asyncio.run(main())
Przykłady
import asyncio
async def main():
async with asyncio.TaskGroup() as group:
first = group.create_task(asyncio.sleep(0, result=3))
second = group.create_task(asyncio.sleep(0, result=8))
print(first.result() + second.result())
asyncio.run(main())
Wynik
11
KeyboardInterrupt i SystemExit są zgłaszane osobno.