Отдельно разберём 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
#quoteoftheday
💬“If you are not embarrassed by the first version of your product, you launched too late.” — Reid Hoffman, LinkedIn co-founder
🚀 While you are redesigning your logo for the tenth time, someone else is already monetizing their product at the MVP stage.
Follow Startup Base to stay updated on startups, opportunities, and the latest trends.
@startupbaseuz
LinkedIn | Facebook | Instagram | Website
#quoteoftheday
💬“Agar mahsulotingizning birinchi versiyasidan uyalmasangiz, siz uni juda kech ishga tushiribsiz”—Rid Hofman, LinkedIn asoschilaridan biri
🚀Siz logotipni o‘ninchi bor o‘zgartirayotganingizda, kimdir allaqachon mahsulotini MVP’da pullayapti.
Startaplar, ularga oid imkoniyatlar va trendlardan xabardor bo‘lish uchun Startup Base’ni kuzatib boring.
@startupbaseuz
LinkedIn | Facebook | Instagram | Website
☀️#Quoteoftheday
😇“Don't let yesterday take up too much of today.”
- Will Rogers
❤️@QuotesPoint
✅@Quotes_Positive_Inspirational
✔️@Quotes_Motivational_Inspiring
☀️#Quoteoftheday
😇“You cannot protect yourself from sadness without protecting yourself from happiness.”
- Jonathan Safran Foer
❤️@QuotesPoint
✅@Quotes_Positive_Inspirational
✔️@Quotes_Motivational_Inspiring
☀️#Quoteoftheday
😇“It's up to you how far you go. If you don't try, you'll never know!”
- Merlin, "Sword in the Stone"
❤️@QuotesPoint
✅@Quotes_Positive_Inspirational
✔️@Quotes_Motivational_Inspiring
☀️#Quoteoftheday
😇“Pursue the things you love doing and then do them so well that people can’t take their eyes off of you.”
- Maya Angelou
❤️@QuotesPoint
✅@Quotes_Positive_Inspirational
✔️@Quotes_Motivational_Inspiring
☀️#Quoteoftheday
😇“This is your life. Do what you love, and do it often.”
- Holstee Manifesto
❤️@QuotesPoint
✅@Quotes_Positive_Inspirational
✔️@Quotes_Motivational_Inspiring
☀️#Quoteoftheday
😇“Focus is the art of knowing what to ignore.”
- James Clear
❤️@QuotesPoint
✅@Quotes_Positive_Inspirational
✔️@Quotes_Motivational_Inspiring
☀️#Quoteoftheday
😇“Always remember that the future comes one day at a time.”
- Dean Acheson
❤️@QuotesPoint
✅@Quotes_Positive_Inspirational
✔️@Quotes_Motivational_Inspiring