Отдельно разберём 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
🌎 The disappearance of the Sodder children in 1945 remains unsolved. Five siblings vanished after a house fire in Fayetteville, West Virginia. Investigators found no remains in the ash, and sightings were later reported but never verified. A billboard seeking answers stood along Route 16 for decades. ✨
#history⚡#disappearance⚡#mystery
👉subscribe Interesting Planet
🌎 In 2009, French aircraft Air France Flight 447 disappeared over the Atlantic during a flight from Rio de Janeiro to Paris. All 228 people on board died. The plane's wreckage was not found for nearly two years, when deep-sea searches located the main debris field at a depth of 3,900 meters. ✨
#aviation⚡#disappearance⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 In 1815, the British brig HMS Rosalie was found abandoned and drifting near the Bahamas. The ship’s sails were set, and cargo untouched, but not a single crew member was found onboard. Official records note that the ship’s logbook and personal belongings were still present when discovered. ✨
#disappearance⚡#maritime⚡#mystery
👉subscribe Interesting Planet
🌎 In 1973, Australian pilot Frederick Valentich disappeared while flying a Cessna 182L over Bass Strait. During radio contact, he reported a strange, unidentified craft circling his plane before transmission was lost. Despite a large search, neither Valentich nor his aircraft were ever found. ✨
#disappearance⚡#aviation⚡#australia
👉subscribe Interesting Planet
👉more Channels
🌎 In 1872, the Mary Celeste was found adrift in the Atlantic Ocean—its crew vanished without a trace, leaving food, cargo, and the ship untouched. This unsolved maritime mystery has puzzled historians ever since. ✨
#disappearance⚡#ship⚡#mystery
👉subscribe Interesting Planet
🌎 In 1925, British explorer Percy Fawcett vanished in Brazil's Amazon rainforest while searching for the lost city of "Z." Fawcett, his son, and a companion were last seen near the Upper Xingu River. Despite dozens of rescue missions over decades, no confirmed trace of the expedition was ever found. ✨
#amazon⚡#disappearance⚡#exploration
👉subscribe Interesting Planet
👉more Channels