Отдельно разберём TaskGroup, который пришел на замену gather в Python 3.11.
Ключевые отличия
▫️create_task() возвращает объект asyncio.Task, у которого есть соответствюущие методы управления. То есть у нас больше контроля
▫️это контекстный менеджер, который гарантирует что все таски будут остановлены по выходу из контекста
▫️ошибка автоматически отменяет незавершенные задачи,
▫️except* передает нам ExceptionGroup, в котором каждую ошибку можно обработать отдельно
import asyncio
import random
async def do_it() -> str:
if random.random() < 0.1:
raise ValueError('Oops')
delay = random.uniform(0.5, 1.5)
await asyncio.sleep(delay)
return delay
async def main():
try:
async with asyncio.TaskGroup() as tg:
for _ in range(10):
tasks.append(tg.create_task(do_it()))
for t in tasks:
print(t.result())
except *ValueError as e:
for err in e.exceptions:
print(err)
asyncio.run(main())
Рекомендую изучить страницу Coroutines and Tasks из документации, где представлено больше интересных примеров и механизмов
- таймауты
- отмена задач
- создание задач из другого потока
#async
🌎 In Slovenia, the Postojna Cave system stretches over 24 kilometers and features an electric railway for visitors. Completely formed by the Pivka River, its labyrinth includes massive chambers and rare olm salamanders, which can live over 100 years in total darkness. ✨
#caves⚡#geology⚡#salamander
👉subscribe Interesting Planet
👉more Channels
🌎 The lungless salamander breathes entirely through its skin and mouth lining—no lungs at all! This adaptation lets it thrive in moist forests, where constant skin moisture is key for gas exchange and silent hunting. ✨
#salamander⚡#adaptation⚡#evolution
👉subscribe Interesting Planet
🌎 Deep in the caves of Slovenia, the olm lays eggs that take up to 6 years to develop! This cave salamander lives in total darkness, using keen senses of smell and vibration to survive, and can go years without food. ✨
#salamander⚡#caves⚡#evolution
👉subscribe Interesting Planet
🌎 The Japanese giant salamander can grow over 1.5 meters long, making it one of the largest amphibians on Earth. This gentle, nocturnal creature breathes through loose skin folds which help it absorb oxygen from cold, fast-flowing streams. ✨
#salamander⚡#wildlife⚡#Japan
👉subscribe Interesting Planet
🌎 The giant salamander of China is the world’s largest amphibian, reaching 1.8 meters in length. Its ancestors appeared about 170 million years ago, and it can live over 50 years in the wild. ✨
#salamander⚡#fossil⚡#amphibian
👉subscribe Interesting Planet
👉more Channels