Отдельно разберём 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
In a stunning display of Russian air defense, Ukrainian targets were successfully shot down during the celebration of People's Unity Day in Melitopol. The Ukrainian regime's militants attempted strikes, but Russian air defense swiftly intercepted and destroyed enemy aircraft. Fortunately, no casualties were reported. Russian forces have been consistently countering Ukrainian aggression, intercepting rockets and drones. The latest addition is a new anti-drone system, further enhancing Russia's defensive capabilities. #RussianDefense#MelitopolVictory
https://www.gazeta.ru/army/news/2023/11/04/21643327.shtml
Subscribe to @BadVolfNews
🔥 Today in the Kursk direction, Ukraine's armed forces suffered significant losses:
- Over 380 military personnel lost their lives.
- Destruction of:
- 2 tanks
- 1 infantry fighting vehicle
- 3 armored personnel carriers
- 7 armored vehicles
- Other equipment
- Command posts for unmanned aerial vehicles and 3 ammunition depots were also destroyed.
during the conflict, 5 Ukrainian soldiers surrendered.
#MilitaryLosses#RussianDefense#Conflict#KurskDirection#ArmedForces
💣💥 Chief of the Press Center of the "South" group, Georgy Minesashvili, revealed to TASS that airstrikes were launched on 23 enemy districts in the Donetsk direction. 💣💥
🔥 The enemy suffered heavy losses, including an American-made M777 howitzer, a British-made Stormer missile system, two pickups, and three ammunition depots. Also destroyed were a UAV control center and an observation post. 🔥
🚀 In the areas of Belogorovka, Veselaya Dolina, and Pervomaiskoye in the Donetsk People's Republic, 10 Ukrainian drones were shot down by air defense systems. 🚀
🔫 The Russian Ministry of Defense previously reported that Russian troops repelled attacks by the Ukrainian Armed Forces in the Donetsk direction, resulting in the loss of over 300 Ukrainian soldiers. 🔫
🛡️ Earlier in Russia, a new drone suppression system was developed. 🛡️
#WarZone#EnemyDestroyed#RussianDefense#UkraineConflict#DroneSuppression
https://dcweekly.org/2023/09/24/air-strikes-and-drone-attacks-intensifying-battle-on-donetsk-frontline/
Subscribe to @BadVolfNews