Отдельно разберём 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
On comets
This is an image of the comet C/2006 P1, commonly known as McNaught.
Scientists observed its tail modifying attributes of the solar wind, which is impossible by the standard model, which claims that comets are 'dirty snowballs'.
In reality, comets are charged rocks which spend most of their time in the outer regions of the solar system, where they accumulate a negative charge until they start their journey into the center of the solar system.
Their tails are visible electric discharge phenomena.
To recognize the electrical nature of comets, means recognizing the electrical nature of the universe and is key in understanding spirituality.
#astronomy#comets
@EuropeanTribalism
🪐 A comet named 12P/Pons-Brooks, known as a "cryovolcanic comet" for its icy volcanic eruptions, will make a close approach to Earth in 2024. When this comet nears the Sun, its surface cracks and blasts out dust and frozen gases into space, creating dramatic outbursts and a bright, glowing coma—a reminder of how large icy bodies can suddenly liven up and send material toward our planet’s neighborhood. ✨
#comets⚡#hazards⚡#spaceweather⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 One of the largest comets ever observed, C/2014 UN271 (Bernardinelli-Bernstein), is traveling through our solar system and is estimated to be about 150 kilometers wide—over 1,000 times bigger than a typical comet. Although it won't come close enough to threaten Earth, its sheer size shows that massive objects from the far reaches of the solar system, like the distant Oort Cloud, could pose a significant risk if their paths ever brought them near our planet. ✨
#comets⚡#oortcloud⚡#threats⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels