Отдельно разберём 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
🏆Последние победители в номинации «Альбом года» на премии #GRAMMY:
2026: Bad Bunny – DeBÍ TiRAR MáS FOToS
2025: Beyoncé – Cowboy Carter
2024: Taylor Swift – Midnights
2023: Harry Styles – Harry's House
2022: Jon Batiste – We Are
2021: Taylor Swift – folklore
2020: Billie Eilish – When We All Fall Asleep, Where Do We Go?
Adele makes her music comeback
Adele has made her highly-anticipated music comeback with 'Easy On Me' from her new album '30'
#News#Reuters#Adele#Grammy#EasyOnMe
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
🗓January 30 marks the birthday of Tyla, a South African singer and songwriter 🇿🇦🎶
Born in 2002 in Johannesburg, South Africa, Tyla is known for her distinctive voice and a unique sound that blends Afro-pop and R&B.
Her breakthrough came with the hit Getting Late, which brought her international attention and marked the beginning of her rapid rise.
🏆 In 2024, Tyla won a Grammy Award for her song Water, a defining milestone in her career and a symbol of her global success.
Tyla’s music continues to resonate with audiences worldwide, and her fan base keeps growing.
📸 Photo: womanandhomemagazine.co.za
📹Getting Late:
https://www.youtube.com/watch?v=v6Tct3AAre0
📹Water:
https://www.youtube.com/watch?v=TSsFB241BHs
🎧More songs by Tyla (audio only):
https://www.youtube.com/watch?v=zEm7pFqfRWA
#Tyla#SouthAfrica#Music#AfroPop#RAndB#Grammy#GlobalMusic
🗓30 января — день рождения южноафриканской певицы и автора песен Тайлы🇿🇦🎶
Тайла родилась в 2002 году в Йоханнесбурге (ЮАР). Её визитная карточка — яркий голос и уникальный стиль на стыке афро-попа и R&B.
Музыкальный взлёт певицы начался с хита Getting Late («Близится вечер»), который привлёк к ней международное внимание.
🏆 В 2024 году Тайла была удостоена премии «Грэмми» за песню Water («Вода») — ключевой момент в её карьере и подтверждение мирового признания.
Музыка Тайлы находит отклик у слушателей по всему миру, а число её поклонников продолжает расти.
📸 Фото: womanandhomemagazine.co.za
🎬Getting Late: https://www.youtube.com/watch?v=v6Tct3AAre0
🎬Water: https://www.youtube.com/watch?v=TSsFB241BHs
🎧Другие песни Тайлы (аудио, не клипы):
https://www.youtube.com/watch?v=zEm7pFqfRWA
#Tyla#Тайла#ЮАР#Музыка#ПопМузыка#RAndB#AfroPop#Grammy