Отдельно разберём 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
[WEVERSE DM] | 260511
🐧: I’ll leave a goodnight voice message
🐧: I’m leaving one after a long time
🐧: It’s kinda embarrassing listening to my own voice
🐧: Hehe ☺️
🐧🔈 Goodnight MOA ♡
#투모로우바이투게더#TOMORROW_X_TOGETHER#HUENINGKAI
[WEVERSE DM] | 260511
🐧: Pictures I took during Countless Friends
🐧: Both the episodes so far have been successful
🐧: (cute tone) I’ve been in touch with both of them
#투모로우바이투게더#TOMORROW_X_TOGETHER#HUENINGKAI
[WEVERSE DM] | 260508
🐧: 🎁
🐧: A present hehe
🐧: Ah this isn’t right now haha
🐧: It’s an old selfie
🐧: When I was on stand by during the shoot
🐧: That’s right that’s right, during ‘Countless Friends’
#투모로우바이투게더#TOMORROW_X_TOGETHER#HUENINGKAI
[WEVERSE DM] | 260419
🐧: For real
🐧: Out of the 4 days
🐧: I think today’s outfit & hair was the best
🐧: (cute tone) it was really pretty
#투모로우바이투게더#TOMORROW_X_TOGETHER#HUENINGKAI
[WEVERSE DM] | 260318
🐧: Yup I went on a short trip
🐧: I stopped by the pokémon center and bought morr (*typo for ‘more’) plushies lol
🐧: So cute, right?
🐧: These are the friends I bought this time
🐧: As expected I guess I can’t help myself
🐧: Every time I look at plushies, it makes me happy
🐧: I’m going to try playing pokopia
🐧: Because it kinda looks fun
🐧: I should try decorating the houses
🐧: And things like that hehe apparently it’s a healing game
#투모로우바이투게더#TOMORROW_X_TOGETHER#HUENINGKAI