Отдельно разберём 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
Vaccines strengthen our immunity and protect us from many preventable diseases. 💪
They help keep individuals, families, and communities safe and healthy.
✅️Ensure you and your loved ones stay up to date and complete your vaccine doses — it’s one of the best ways to stay protected and live healthy!
Stay informed. Stay protected. Stay healthy. ✔️
# #NCDCNigeria#StayProtected#HealthyNigeria#HealthyLiving
#WellnessWednesday: Boost Your Immunity, Stay Protected! 🛡️🥦
Your immune system is your first line of defense against infections, including Mpox and other diseases. Keep it strong with these healthy habits:
🥗 Eat a balanced diet rich in fruits, vegetables, and proteins
🚶♂️ Stay active with regular exercise
💧 Hydrate: drink plenty of water daily
😴 Get enough sleep to support immune function
🧼 Practice good hygiene: wash hands frequently and keep surroundings clean
💉 Stay up to date on vaccinations where applicable
A strong immune system means a healthier you! Take charge of your wellness today.
#WellnessWednesday#HealthyLiving#BoostYourImmunity#StayProtected#NCDCNigeria
#WellnessWednesday: Boost Your Immunity, Stay Protected! 🛡️🥦
Your immune system is your first line of defense against infections, including Mpox and other diseases. Keep it strong with these healthy habits:
🥗 Eat a balanced diet rich in fruits, vegetables, and proteins
🚶♂️ Stay active with regular exercise
💧 Hydrate—drink plenty of water daily
😴 Get enough sleep to support immune function
🧼 Practice good hygiene—wash hands frequently and keep surroundings clean
💉 Stay up to date on vaccinations where applicable
A strong immune system means a healthier you! Take charge of your wellness today.
#WellnessWednesday#HealthyLiving#BoostYourImmunity#StayProtected#NCDCUpdates
#Yellow fever is a serious but vaccine preventable viral disease.
It spreads through the bite of infected mosquitoes
Protect yourself by:
▶️Getting vaccinated💉
▶️Maintaining a clean environment to stop mosquitoes from breeding.
▶️ Use insect repellent and sleep under treated nets to avoid mosquito bites.
⚠️ Report early to a nearby health facility if you feel unwell with symptoms like fever, headache, or yellowing of the eyes/skin.
#YellowFever#StayProtected#HealthyNigeria#NCDCNigeria