CKTIS / Python
asyncio.TaskGroup
Fasst mit group.create_task erzeugte Tasks in einem Bereich zusammen.
Version: Python 3.14; repository image, production runtime not attested
Syntax
async with asyncio.TaskGroup() as group:
task = group.create_task(coro)Fasst mit group.create_task erzeugte Tasks in einem Bereich zusammen.
Die Gruppe kann den Block trotz abgebrochenem Kind normal verlassen. Dessen result() löst dann CancelledError aus. Beim Verlassen werden alle Kinder erwartet und erfolgreiche Ergebnisse stehen bereit. Der erste gewöhnliche Fehler bricht Geschwister ab, nach dem Aufräumen folgen Fehler in ExceptionGroup oder BaseExceptionGroup. Ein einzelner Kindabbruch löst das nicht aus.
KeyboardInterrupt und SystemExit werden gesondert weitergegeben.
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())
Beispiele
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())
Ergebnis
11
KeyboardInterrupt und SystemExit werden gesondert weitergegeben.