Отдельно разберём 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 the Mariana Trench, the deepest part of the ocean, researchers have found strange microbial life living over 10,900 meters below the surface. These microbes survive by breaking down chemicals from rocks, not sunlight, and help recycle nutrients in this harsh environment. ✨
#ocean⚡#trench⚡#microbes
👉subscribe Interesting Planet
👉more Channels
🌍 Some bacteria and fungi live deep in rocks of the lithosphere, far below where sunlight reaches. These life forms connect the biosphere to Earth's rocky layer in ways once thought impossible. ✨
#lithosphere⚡#biosphere⚡#microbes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Earth’s spheres aren’t fixed—they overlap at microbe level. Extremophiles, tiny life forms, live deep underground rocks, linking the biosphere to the lithosphere in some of Earth's harshest zones. ✨
#lithosphere⚡#biosphere⚡#microbes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌎 Vibrant hot springs in Yellowstone glow with brilliant colors thanks to heat-loving bacteria called thermophiles. These microbes produce pigments that create beautiful bands of green, yellow, and orange around the steaming pools. ✨
#Yellowstone⚡#microbes⚡#geology
👉subscribe Interesting Planet
🌎 The salt-loving halophiles of California’s pink Lake Hillier thrive where few others survive. These tiny microbes give the lake its vivid color by producing pigments that protect them from extreme salt and sunlight—turning the water a bubblegum pink! ✨
#microbes⚡#pigment⚡#lakes
👉subscribe Interesting Planet
After death, human microbes survive in soil and help break down the body. They work with soil microbes to speed up decomposition and recycle nitrogen, which plants need to grow. These microbes can live in the soil for months or years, turning dead bodies into nutrients that support new life. 🌱🦠💀
[Source]
@googlefactss#Decomposition#Microbes#Soil#NitrogenCycle#Ecosystem