Отдельно разберём 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
📢TODAY!
What happens when the #antimicrobial drugs used in treating infections in humans & animals become ineffective?
At 6 PM, join the DRASA - Dr. Ameyo Stella Adadevoh Health Trust 's conversation on "You, Me, and The Supergerms: Preventing Antimicrobial Resistance Together"
🔗Share
https://bit.ly/DRASAWAAW22
ICYMI
"#AntimicrobialResistance requires the efforts of the Human, Animal & Environmental sectors & also a whole-of-society approach to manage"
Watch our #AMR programme coordinator, Dr Tochi Okwor as she discusses the impact of #antimicrobial misuse in Nigeria.
🔗
https://youtu.be/B1GgpIuoE2Y
#Antimicrobial Resistance (AMR) is a global threat.
✨As a healthcare professional, always carry out the correct test before prescribing.
Accurate diagnosis helps prevent resistance☑️
Always test before treating!!
#StopAMR#StaySafe#NCDCNigeria
#Antimicrobial Resistance (AMR) is a growing global health threat — but together, we can prevent it! 🚫💊
👉 Don’t self-medicate
👉 Complete your prescriptions
👉 Don’t share leftover drugs
👉 wash hands frequently with soap under running water
👉 Stay protected with vaccines
Let’s all take responsibility in the fight against AMR. 💪🌍
#StopAMR#StaySafe#NCDCNigeria
As an individual, what can you do to prevent #Antimicrobial Resistance?
Our #AMR programme manager @beeodune will be live alongside other panellists on @drasatrust's @XSpaces discussion to speak on:
“Supergerms and the Future of Infection :
🗓️ Today, 24th November
🕙6:00 PM
🔗Join the conversation via:
http://bit.ly/LearnWithDRASA7
#WAAW2023#WorldAMRAwarenessWeek