Отдельно разберём 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
#Idiom
💢Go off on a tangent
Or
💢 Go off at a tangent
🔰If a person or piece of writing goes off on a tangent or goes off at a tangent, they start saying or thinking something that is not directly connected with what they were saying or thinking before
💠Note:-
In geometry, a tangent is a straight line which touches a curve at one point
🕸 Ex:- Our teacher would occasionally go off on a tangent and start talking about something totally unrelated to the textbook.
💠Note:-
You can use other verbs instead of go
🕸 Ex:- The book's theme wandersoff on a tangent now and then.
#Idiom
🕸People in society🕸
❄️A self-made man
♣️ A person who is rich and successful because they have worked hard, not because they were born into a rich family
❄️The chattering classes
♣️ Educated people who enjoy discussing social, political and cultural issues
❄️A second-class citizen
♣️ Someone is treated as if they are less important than others in society
❄️The grass roots
♣️ Ordinary people in a political or sporting organisation, not the leaders
❄️ The silent majority
♣️ A large number of people who do not express their opinions publicly
❄️ The (men in) grey suits
♣️ People in business or politics with a lot of influence or power, although they are not well known to the public
❄️Public enemy number one
♣️ Smth or someone that a lot of people dislike or disapprove of
❄️New kid on the block
♣️ Someone who is new in a place or organisation and has many things to learn about it (informal).
#Idiom
💢Even exchange: a trade of equal value; when you return something and take something else that costs the same price
✨ Ex: If you return that jacket and get this sweater instead, it will be an even exchange. They're both $39.99.
#Idiom
💢(To) steer clear of: to avoid, usually due to a bad experience
✨ Ex: Mark got food poisoning at O'Reilly's? We'd better steer clear of that place from now on!
#Idiom
💢(To) have the magic touch: to have talent at doing something; to be able to do something difficult.
✨ Ex: You can't open that bottle? Give it to Ivan. He usually has the magic touch.