Отдельно разберём 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
🌎 Wild African grey parrots are known to mimic not only human speech but also the calls of up to 30 other bird species in their habitat. This ability helps them integrate into mixed-species flocks and avoid predators by confusing potential threats. Parrots’ vocal learning is so advanced that some individuals can remember and use sounds for decades. ✨
#parrots⚡#intelligence⚡#communication
👉subscribe Interesting Planet
👉more Channels
🌎 African grey parrots rank among the best animal communicators. Scientific studies show they can understand hundreds of words, use them in context, and even grasp abstract concepts like “same” and “different.” One famous parrot, Alex, correctly identified shapes and colors and understood the concept of zero. ✨
#parrots⚡#cognition⚡#communication
👉subscribe Interesting Planet
👉more Channels
🌎 African grey parrots can solve multi-step logic puzzles and use words in meaningful context. In experiments, these parrots matched human toddlers in understanding basic concepts. The largest recorded vocabulary for one individual exceeded 1,000 words. ✨
#parrots⚡#animalbehavior⚡#cognition
👉subscribe Interesting Planet
👉more Channels
🌎 Parrots like the African grey can learn hundreds of words and use them to solve problems or request specific items. Studies show Alex, a famous African grey, identified colors, shapes, and quantities—demonstrating complex reasoning once thought exclusive to humans. ✨
#parrots⚡#cognition⚡#language
👉subscribe Interesting Planet