Junior — Middle
Have you worked with task groups in asyncio for managing asynchronous calls?
sobes.tech AI
Answer from AI
In Python asyncio, there is no built-in concept of a "task group" as a separate object, but to manage multiple asynchronous calls, functions like asyncio.gather() or asyncio.wait() are often used. They allow running and controlling multiple coroutines simultaneously.
For example, to run several tasks and wait for their completion:
import asyncio
async def task(id):
await asyncio.sleep(1)
return f"Task {id} done"
async def main():
tasks = [task(i) for i in range(5)]
results = await asyncio.gather(*tasks)
print(results)
asyncio.run(main())
If "task groups" refers to managing a set of tasks, then asyncio.TaskGroup (starting from Python 3.11) can be used, which simplifies creating and managing a group of tasks:
import asyncio
async def task(id):
await asyncio.sleep(1)
print(f"Task {id} done")
async def main():
async with asyncio.TaskGroup() as tg:
for i in range(5):
tg.create_task(task(i))
asyncio.run(main())
Thus, TaskGroup helps conveniently manage the lifecycle of a group of asynchronous tasks.