Отдельно разберём 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
251121 || THE STAR 𝕏 UPDATE
[Show Me Your Bag Teaser] Idol merchant, Miyeon from i-DLE appears🤗 From gifts received from a Japanese actor to vintage digital cameras and mouthwash, a big reveal of her beloved items👜
'Actually, I brought these because I wanted to show off🥹'
Miyeon's Show Me Your Bag explodes with cuteness × loveliness, just like her owner✨
Releasing on November 22 at 8 PM on The Star's YouTube💕
#미연#MIYEON
–🦋
── @GIDLE_UPDATE ──
251105 || SOHU KOREA 𝕏 UPDATE
🐽 Piglet meme 5 times in a row!
😎 Seominjung rap personal skill laughter challenge!
💕 Wony & Sana try drawing in 3 seconds!
Save the pretty selfie of Miyeon and the fox doll 🦊 and enjoy the full SOHU KOREA interview!! 🥳🥳
YouTube: https://www.youtube.com/watch?v=iKPDxbxodQA
#아이들#idle#미연#MIYEON
–🦋
── @GIDLE_UPDATE ──