Отдельно разберём 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 Mongolian steppes have supported nomadic herding for centuries, with grasslands shaped by grazing animals and seasonal movement. This partnership keeps both wildlife and pastures thriving naturally. ✨
#nature⚡#society⚡#grasslands⚡#geography⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Temperate grasslands like the Eurasian steppes can experience temperature swings of over 40°C between summer and winter, creating some of the planet’s most extreme seasonal contrasts. ✨
#grasslands⚡#savanna⚡#climate⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Pampas grasslands in South America are so fertile they support one of the world’s largest cattle industries and can produce up to seven harvests of grass each year, fueling global food markets. ✨
#grasslands⚡#agriculture⚡#SouthAmerica⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Africa’s Miombo savanna covers over 2.7 million square kilometers—about the size of Argentina. Its woodlands support hundreds of unique butterfly species found nowhere else on Earth. ✨
#savanna⚡#grasslands⚡#ecosystems⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Some grassland plants grow deep roots reaching over 2 meters underground. These roots help the plants survive drought and anchor soil, making grasslands some of the most erosion-resistant landscapes. ✨
#grasslands⚡#savanna⚡#ecology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Grasslands cover about 40% of Earth’s land surface and are found on every continent except Antarctica. Some of the world’s richest soils, called mollisols, form in temperate grasslands. ✨
#grasslands⚡#savanna⚡#soil⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Some grassland soils are so fertile they can support crops for decades without added fertilizer. These deep, dark soils store huge amounts of carbon, helping stabilize the global climate. ✨
#grasslands⚡#soil⚡#carbon⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Argentina’s Pampas are vast temperate grasslands that grow some of the world’s richest soils. These grasslands support massive cattle herds and store huge amounts of carbon underground. ✨
#grasslands⚡#pampas⚡#carbon⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels