Отдельно разберём 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
#Rivers
SyrDarya and AmuDarya on the brink: water scarcity is reshaping regional policy
The water-energy crisis in Central Asia is becoming one of the key challenges for the region, including Uzbekistan. According to Kassym-Jomart Tokayev, water availability per capita in the region has decreased by nearly 30% over the past 20 years. Climate change is intensifying the pressure: glaciers in the Pamir and Tien Shan mountains, which feed the Amu Darya and Syr Darya rivers, are rapidly melting. An additional source of concern is the construction of the Qosh Tepa Canal in Afghanistan, which could significantly reduce the flow of the Amu Darya and affect water supply in Uzbekistan and Turkmenistan.
The situation is further complicated by an outdated water management system inherited from the Soviet era. Previously, a “water-for-energy” mechanism functioned in the region: Kyrgyzstan and Tajikistan stored water in summer for irrigation needs in Uzbekistan, Kazakhstan and Turkmenistan, receiving energy resources in winter in return. After the collapse of the Soviet Union, this system largely broke down. Today the situation is further complicated by large hydropower projects such as Rogun Dam and Kambarata-1 Hydropower Plant. While these projects strengthen the energy independence of upstream countries, they also raise concerns among downstream states, including Uzbekistan.
Experts say the region now faces a choice: escalating water conflicts or strengthening cooperation. For Uzbekistan, water is directly linked to food security, agriculture, and environmental stability. One proposed solution is the creation of a new regional mechanism for managing transboundary water resources and the joint implementation of water-saving technologies. Without such cooperation, water scarcity could become a major challenge for the sustainable development of the entire Central Asian region. 💧🌍
☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot
Instagram | Facebook | Twitter | Sayt | Youtube.
#Nature
#Rivers
Amazon's Meeting of Waters
Dual-Toned Rivers of Amazon
Experience the mesmerizing natural phenomenon at
the 'Meeting of Waters’ near Manaus. Here, the dark
Rio Negro and the lighter Amazon River flow in
parallel, refusing to mix for miles, creating a stunning
dual-toned effect. The surrounding landscape
features a prominent plateau and mesa, adding to
the dramatic beauty of this unique confluence. The
vibrant sunset enhances the contrasting colors of
the rivers, making it a truly unforgettable sight. This
natural wonder showcases the power and beauty of
the Amazon rainforest.
🌍 The world’s shortest river, the Roe River in Montana, flows only about 61 meters from its source to its mouth. Despite its tiny length, it’s officially recognized as a river. ✨
#rivers⚡#hydrology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌎 Deep in the Brazilian rainforest, the Encontro das Águas marks where the dark Rio Negro meets the sandy Amazon River. The two rivers flow side by side for 6 kilometers without mixing due to differences in temperature, speed, and density. ✨
#mysteries⚡#rivers⚡#Brazil
👉subscribe Interesting Planet
👉more Channels
🌍 The Amazon River’s water travels over 6,400 kilometers from Andes glaciers to the Atlantic, but some of its rain comes from clouds recycled multiple times through plant evaporation along the journey. ✨
#hydrology⚡#rivers⚡#rainforest⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Rivers in the Amazon basin recycle rainwater so efficiently that a single water droplet may fall as rain and evaporate back into the sky up to seven times before leaving the forest. ✨
#hydrology⚡#rainforest⚡#rivers⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Water trapped as snow and ice in the Himalayas slowly melts each spring, feeding rivers that bring life to billions across Asia. This seasonal meltwater is key to the region’s water cycle. ✨
#hydrology⚡#rivers⚡#glaciers⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Lena River in Siberia creates the largest natural river delta in the Arctic, spreading into thousands of channels and wetlands that provide vital nesting grounds for millions of migratory birds. ✨
#rivers⚡#wetlands⚡#Arctic⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Okavango Delta in Botswana is one of the few major river deltas that forms entirely inland, creating a lush wetland oasis in the middle of the Kalahari Desert. ✨
#rivers⚡#wetlands⚡#delta⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Germany’s Upper Middle Rhine Valley is a UNESCO heritage site where castles, vineyards, and medieval villages line steep riverbanks. Its landscape tells centuries of human and natural interaction. ✨
#heritage⚡#landscape⚡#rivers⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Africa’s Lake Victoria is the largest tropical lake in the world. Its outflow forms the start of the Nile River, which journeys over 6,600 kilometers north to the Mediterranean Sea. ✨
#lakes⚡#rivers⚡#Africa⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels