Отдельно разберём 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
Don’t forget to bring along your reusable shopping bag when you’re out buying your Lunar New Year goodies. Together, we can have a sustainable Year of the Rabbit! 🐰
#BYOB#SayYEStoWasteLess#TowardsZeroWaste
Don’t get a red card especially when it comes to saving the Earth! Say NO to disposables, and YES to reusables.
Together, we can move #TowardsZeroWaste and create a #SustainableSG! #SayYEStoWasteLess#BYOB
This Halloween, make your carbon footprint less scary!
🍿 Having a spooky movie night? Bring along reusable popcorn containers and cups.
👻 Hitting a few haunted houses? Don't forget to keep hydrated with a reusable bottle.
🍭 And if you’re thinking of hitting the sweet shops, keep a reusable bag handy.
#SustainableSG#BYO#BYOB
Bring your reusable bag when you go shopping! Every action counts when it comes to saving planet Earth, and a little goes a long way when it comes to savings 💰
Show the Earth and your wallet some love! #SayYEStoWasteLess#BYO#BYOB
Lock screen reminders are the new sticky notes. So set a trendy reminder to bring your own reusable bag before heading out!
Let’s save the planet, one bag at a time 🛍#BYO#BYOB#SayYEStoWasteLess
Remember to bring your reusable bags when you’re heading out to buy New Year goodies.
This way, you’ll save money while saving the environment. Cheers to a clean, green and prosperous new year. 🧧
#BYOB#SustainableSG#TowardsZeroWaste#LunarNewYear2024
#DidYouKnow the average family in Singapore that buys groceries weekly uses about 1,248 single-use plastic bags annually? 😱
Let’s #SayYEStoWasteLess by bringing along reusable bags when heading out! #BYO#BYOB
Santa’s not the only one with a reusable bag!
When visiting the mall to shop, let’s bring our reusable bags. Together, we can ensure fa-la-la-la-la, la-la-la-less packaging waste. 🛍️
#SayYEStoWasteLess#TowardsZeroWaste#BringYourOwn#BYO#BYOB
Level up your eco-game! ♻️💪 Tote-ally rockin’ a reusable bag = Saving money, slashing trash and giving our environment a healthy splash! 🌿🌏
#BYOB#ZeroWasteNation#Sustainability#SayYEStoWasteLess
For more news and updates on government announcements, follow us on WhatsApp Channels at go.gov.sg/wa-channels!😊
250911 || JohnMaat 𝕏 UPDATE
BYOB Season 3 Final Chef👨🍳
˗ˋˏ YUQI i-dle ˎˊ˗
Yuqi (in charge of all things 𝒮𝐸𝒳𝒴 ⒸⓊⓉⒺ for IDLE)
Would you like to watch the BYOB Wave Show?
> Gi
> Ginio
🔥15 episodes will be released tomorrow at 10 AM (KST)
🔗http://youtube.com/@John_maat
#BYOB#박준형#브라이언
#아이들#idle#우기#YUQI
–🦋
── @GIDLE_UPDATE ──