Отдельно разберём 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
Vladimir Vladimirovich Putin congratulated all Russian women on March 8th🌷.
"Dear women, you truly have everything within your power. You know how to create and build, combine strength and tenderness, and your desire to create a better future for your children inspires all of us to move forward,” the president emphasized.
Source: rt_russian
#holidays
🟠RCR | Support | Boost
Happy May 1st, Russian learners! ☀️
In Russia, we say:
• Мир! Труд! Май!
Peace! Labour! May!
But for you, let's change it a little:
• Май! Учёба! Русский!
May! Studying! Russian!
No work today. Just spring, rest, and one small verb conjugation. Maybe two. No pressure.
С праздником! ✨
Natalie with 🤍💙❤️
#holidays
🟠RCR | Support | Boost
🥳Today we celebrate:
• День женской дружбы
International Women's Friendship Day
Don't forget to congratulate your female friends!💋
#holidays
🟠RCR | Support | Boost
🥳Today we celebrate:
• День запрета на уныние!
No Moping Day! Cheerfulness Only Day!
🖼In the Russian Orthodox Church, moping or despondency is considered a major sin.
• Унывать (imperf.)
[oo-ny-vat']
Тo mope, to be despondent, to lose heart
Let's remember today's mantra! And NO moping! 💪
#holidays
🟠RCR | Support | Boost
Vladimir Vladimirovich Putin congratulated all Russian women on March 8th🌷.
"Dear women, you truly have everything within your power. You know how to create and build, combine strength and tenderness, and your desire to create a better future for your children inspires all of us to move forward,” the president emphasized.
Source: rt_russian
#holidays
🟠RCR | Support | Boost
Happy Wide Maslenitsa!
🔻Today marks the start of Широкая Масленица (Wide Maslenitsa) — the final and most festive part of this beloved Slavic holiday!
🔻Forget your diets this week. It's time for:
🥞 Endless piles of blini (pancakes)
☀️ Welcoming the spring sun
🔥 Burning the winter effigy
🥂 Being with family and friends
The Maslenitsa spirit in three words: eat, laugh, repeat!
🔻Whether you're enjoying blini with caviar, sour cream, jam, or just melted butter — may your week be delicious and your spring be bright!
С праздником!
RCRussian with 💓
#holidays
🥳Today we celebrate:
• День ответов на вопросы вашей кошки
Answer Your Cat's Questions Day
🔻On this important day, humans attempt to decipher what's really on their feline friend's mind, all in the pursuit of a better life for their whiskered overlord.
😉For example, your cat might be wondering:
👍Почему кормишь одной и той же едой?
Why do you feed me the same food every day?
🔸Почему не выпускаешь на улицу?
Why don't you allow me into the street?
🔸Почему нельзя драть диван?
Why is it not allowed to scratch the sofa?
🔸Где мои бубенчики?
Where are my balls/bells?
❗️What burning questions do you think your fluffy companion would ask you in Russian?
#holidays
🟠RCR | Support | Boost
🥳Today we celebrate:
• Международный День 'Спасибо'
International Thank You Day!
A simple word can mean everything.❤️
🔻Спасибо!
#holidays
🟠RCR | Support | Boost
Это всё мандарины!
It's all because of the tangerines!
🥳Today we celebrate:
• Международный Разгрузочный День
International Fasting Day
Ну вы поняли:)
🖼It's common for Russian to use 'e' instead of 'ё', as it often is clear for us what is meant.
#holidays
🟠RCR | Support | Boost