Отдельно разберём 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
❌🟠 Los Giants no anticipan hacer un contrato de nueve cifras para Tatsuya Imai ni para ningún otro lanzador en el mercado esta temporada baja, según Andrew Baggarly.
#️⃣#Giants
🗞 | t.me/MLB_Daily
🏥🌉 Los Giants están colocando a Logan Webb en la lista de lesionados con bursitis en la rodilla derecha, según Alex Pavlovic de NBC Sports Bay Area.
Es la primera vez que Webb está en la lista de lesionados desde 2021.
#Giants#LWebb
🗞 | t.me/MLB_Daily
🟠🤠 Según varios informes, incluidos los de Mark Feinsand de MLB.com, los Giants y el lanzador derecho Tyler Mahle han acordado un contrato de un año.
#️⃣#Giants#Mahle
🗞 | t.me/MLB_Daily
🟠 Según Ken Rosenthal, se informa que los San Francisco Giants están cerca de contratar a Tony Vitello, entrenador principal de Tennessee, como su nuevo manager.
#️⃣#Giants#Vitello
🗞 | t.me/MLB_Daily
🌎 The coconut crab is the world’s largest land-dwelling arthropod, able to crack open coconuts with its powerful pincers. These giant crabs live on islands across the Indo-Pacific, and their climbing and shell-breaking skills help them access food that other animals can’t reach. ✨
#animal⚡#giants⚡#adaptation⚡#islands
👉subscribe Interesting Planet
🪐 Unlike Earth and Mars, giant planets like Jupiter and Saturn do not have solid surfaces—their thick outer layers are made mostly of hydrogen and helium gas, which gradually becomes denser toward the center. These gas giants can have dozens of moons and faint ring systems, and their powerful magnetic fields—especially Jupiter’s, which is the strongest of any planet in our solar system—can trap charged particles, creating intense radiation belts that glow in radio waves. ✨
#Jupiter⚡#Saturn⚡#giants⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Jupiter, the largest planet in our solar system, is so massive that it has over twice the combined mass of all the other planets put together. Its rapid rotation—completing one spin every 10 hours—causes it to bulge noticeably at the equator, creating a distinct flattened shape unlike the more spherical profiles of smaller planets. ✨
#Jupiter⚡#giants⚡#rotation⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Saturn’s rings are made mostly of icy particles ranging from the size of grains of sand to mountains, but what’s remarkable is that these rings are incredibly thin—often only about 10 meters thick compared to their width of up to 282,000 kilometers. Despite their vast size, the rings would still fit comfortably within the gap between Earth and the top of our atmosphere if laid flat. ✨
#Saturn⚡#rings⚡#giants⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels