#asyncio — Public Fediverse posts
Live and recent posts from across the Fediverse tagged #asyncio, aggregated by home.social.
-
asyncio.gatherpropaga a primeira exceção — mas não cancela as outras corrotinas. Elas seguem rodando e podem aplicar efeitos colaterais tardios que nunca aparecem no log. 😬Meu novo post mostra como o
asyncio.TaskGroup(3.11+) resolve isso: cancelamento cooperativo,ExceptionGroup+except*, e adeus ao footgun das tasks coletadas pelo GC.E também: quando
gather(return_exceptions=True)ainda é a escolha certa. -
asyncio.gatherpropaga a primeira exceção — mas não cancela as outras corrotinas. Elas seguem rodando e podem aplicar efeitos colaterais tardios que nunca aparecem no log. 😬Meu novo post mostra como o
asyncio.TaskGroup(3.11+) resolve isso: cancelamento cooperativo,ExceptionGroup+except*, e adeus ao footgun das tasks coletadas pelo GC.E também: quando
gather(return_exceptions=True)ainda é a escolha certa. -
Поставил счётчик на каждый звонок голосового ИИ-агента: 13 сценариев экзамена и себестоимость до копейки
У моего клиента пропущенные звонки берёт голосовой бот. Бот работал, заявки приходили, а я не мог ответить на простой вопрос: сколько стоит один звонок. Рассказываю, как у каждого звонка появился техпаспорт и ценник в рублях, что вскрыл первый живой прогон против зелёного стенда и почему проверка, которая не может упасть, хуже её отсутствия.
https://habr.com/ru/articles/1066792/
#голосовой_агент #llm #наблюдаемость #observability #яндекс_realtime #voximplant #python #себестоимость #asyncio
-
Как я написал свой SMTP‑сервер, чтобы не пропускать сообщения заказчиков с фриланс‑бирж
Я фрилансер, и я ненавижу мониторить биржи. FL, Kwork, Freelance, куча Telegram‑каналов — каждое утро одна и та же рутина. Открываешь вкладку, обновляешь, листаешь, понимаешь что всё мимо, переходишь на следующую. Короче, бесконечная петля. Подсчитал как‑то — два‑три часа в день уходит не на работу. На обновление страниц. Решил автоматизировать. Написал агрегатор, который собирает заказы с четырёх площадок в единую ленту с фильтрами, присылает уведомления в Telegram и пересылает ответы заказчиков из бирж прямо в чат. Под капотом Python 3.13, FastAPI, Vue 3, PostgreSQL. Всё крутится в одном asyncio event loop.
https://habr.com/ru/articles/1064840/
#ython #asyncio #smtp_сервер #фриланс #парсинг_сайтов #fastapi #обход_защиты #telegram_бот #автоотклик #разработка
-
Как отменять задачи в asyncio без зависаний и незавершённой очистки
Отмена задачи кажется простой, пока сервис не зависает при остановке, таймаут не оставляет запрос работать в фоне, а CancelledError исчезает внутри обработчика исключений. Разберём, как устроена кооперативная отмена в asyncio , где ставить точки ожидания и как использовать TaskGroup , timeout и shield , чтобы задачи завершались предсказуемо. Изучить asyncio
https://habr.com/ru/companies/otus/articles/1062504/
#python #отмена_задач #asyncio #CancelledError #асинхронные_задачи #структурная_конкурентность #таймауты #блокирующий_код
-
Why do we always assume a simple shell script is enough to fix a flaky command-line tool? It starts as a quick automation experiment. But as the feature wishlist inevitably grows, so does the complexity of your code. Before you know it, you are asking a basic scripting language to handle time-sensitive guards, conditional retry loops, and external user interactions.
That is how my humble Bash script ended up spawning subshells, tracking process IDs, and trapping SIGTERM just to handle a 2FA prompt timeout on my phone. The script spent half its lines deciding how to exit gracefully, quickly devolving into cryptic gibberish that even my LLM chatbot couldn't comprehend. That was the breaking point where I realized: I need a proper programming language.
Rebuilding the script in Python with asyncio turned out to be an absolute breeze. Thanks to asyncio’s non-blocking event loop, managing timeouts, cleanly forwarding data to stdin during authentication, and gracefully catching shutdown signals became elegant, simple, and incredibly readable. It completely bypassed the need to fiddle with complex cross-process message passing.
Sometimes, keeping personal scripts intentionally crude and un-tested is perfectly fine—so long as they remain structurally sound and readable. If you have been wrestling with complex, brittle process orchestration in Bash, this is your sign to let asyncio save your sanity. Read the full article for a breakdown of the code snippets!
#Python #AsyncIO #SoftwareDevelopment #Bash #Automation #DeveloperLife #CodingHumor #Nix
-
Why do we always assume a simple shell script is enough to fix a flaky command-line tool? It starts as a quick automation experiment. But as the feature wishlist inevitably grows, so does the complexity of your code. Before you know it, you are asking a basic scripting language to handle time-sensitive guards, conditional retry loops, and external user interactions.
That is how my humble Bash script ended up spawning subshells, tracking process IDs, and trapping SIGTERM just to handle a 2FA prompt timeout on my phone. The script spent half its lines deciding how to exit gracefully, quickly devolving into cryptic gibberish that even my LLM chatbot couldn't comprehend. That was the breaking point where I realized: I need a proper programming language.
Rebuilding the script in Python with asyncio turned out to be an absolute breeze. Thanks to asyncio’s non-blocking event loop, managing timeouts, cleanly forwarding data to stdin during authentication, and gracefully catching shutdown signals became elegant, simple, and incredibly readable. It completely bypassed the need to fiddle with complex cross-process message passing.
Sometimes, keeping personal scripts intentionally crude and un-tested is perfectly fine—so long as they remain structurally sound and readable. If you have been wrestling with complex, brittle process orchestration in Bash, this is your sign to let asyncio save your sanity. Read the full article for a breakdown of the code snippets!
#Python #AsyncIO #SoftwareDevelopment #Bash #Automation #DeveloperLife #CodingHumor #Nix
-
After lunch I attended @gi0baro talk about rethinking asyncio for free-threaded Python at @europython 2026🐍
It was a really interesting session with lots of questions from the audience. The very first question even came from Guido van Rossum, which made the discussion even more special. 🎤
Great talk and great discussion! 👏
More info: https://github.com/gi0baro/tonio
-
After lunch I attended @gi0baro talk about rethinking asyncio for free-threaded Python at @europython 2026🐍
It was a really interesting session with lots of questions from the audience. The very first question even came from Guido van Rossum, which made the discussion even more special. 🎤
Great talk and great discussion! 👏
More info: https://github.com/gi0baro/tonio
-
Суть асинхронности в python
Добрых дней, товарищи хабравчане! Изначально я писал этот текст как конспект по асинхронности в пайтоне для самого себя, потому что вещь эта довольно хитрая и не хотелось бы в будущем растерять и забыть знания о ней, когда буду работать с другими языками программирования и фреймворками. Но потом решил попробовать переделать это в формат статьи и опубликовать, потому что сами знаете — когда кому‑то объясняешь, сам начинаешь лучше понимать. Очень надеюсь на конструктивную критику в комментариях, так как хочу сделать эту статью хорошим пособием для новичков или просто людей, которые хотят повторить и закрепить фундаментальные концепции, потому что без их понимания никуда. Итак, приступим.
-
The last few weeks I have spent some time optimizing https://github.com/defnull/multipart which is already one of the fastest python multipart parsers out there.
Result: The next release will be 27-53% faster in the most important benchmark scenarios and 25% faster on average across all tested scenarios. That's a HUGE improvement. It can now parse roughly 10GB of file uploads or 280.000 small text fields per second per core on my 7 years old Ryzen 5 3600 :awesome:
-
The last few weeks I have spent some time optimizing https://github.com/defnull/multipart which is already one of the fastest python multipart parsers out there.
Result: The next release will be 27-53% faster in the most important benchmark scenarios and 25% faster on average across all tested scenarios. That's a HUGE improvement. It can now parse roughly 10GB of file uploads or 280.000 small text fields per second per core on my 7 years old Ryzen 5 3600 :awesome:
-
Современный MQTT-сервис на Python
В Python при выборе библиотеки для работы с MQTT почти всегда приходишь к paho-mqtt . Это зрелый и самый популярный клиент, но его API построен на колбэках, а современное Python-приложение живёт в asyncio : FastAPI, фоновые воркеры, асинхронные клиенты и всё это в одном общем event loop. В одном из IoT-проектов я столкнулся ровно с этим. Мне нужен был MQTT-клиент, который без сложной адаптации встраивается в асинхронное приложение и позволяет работать с подписками как с управляемыми объектами, а не через набор колбэков.
https://habr.com/ru/companies/raiffeisenbank/articles/1052226/
#Python #MQTT #faststream #iot #eventdriven #asyncio #zmqtt #тестирование #асинхронное_программирование #pahomqtt
-
CancelledError — не просто очередная ошибка. Разбираемся, как устроена отмена задач в asyncio
Это первая из двух статей о CancelledError — сигнале отмены задачи. В ней мы остановимся на стандартном asyncio. Узнаем, что на самом деле представляет собой CancelledError , с точки зрения event‑loop. Разберёмся, как работает счётчик отмены ( cancel/uncancel ), на котором построены TaskGroup и asyncio.timeout . Наконец, обсудим проблемы, которые возникают на практике, в первую очередь связанные с asyncio.shield .
-
Погружение в многозадачность Python: процессы, потоки, GIL и асинхронность
Многозадачность кажется простой темой, пока дело не доходит до Python и GIL. В статье разбирается: чем процесс отличается от программы, зачем нужны потоки, что такое ядро процессора и в чём разница между конкурентностью и параллелизмом. Затем – специфика Python: как GIL влияет на потоки, когда стоит использовать процессы, асинхронность или корутины, и чем они отличаются от green threads. Материал сопровождается схемами, рабочими примерами кода и реальными замерами производительности для CPU-bound и I/O-bound задач, а в конце – практические выводы о том, что и когда выбирать.
https://habr.com/ru/articles/1048886/
#python #gil #многопоточность #многопроцессность #asyncio #конкурентность #параллелизм #gevent
-
TIL: asyncio.TaskGroup in Python 3.11+ gives you structured concurrency for free. Spin up multiple async tasks together - if one fails, the rest get cancelled automatically, and exceptions surface as a single ExceptionGroup instead of leaving orphaned tasks hanging around.
Cleaner than asyncio.gather() plus manual error juggling, especially when you're fanning out concurrent calls (DB query + external API, etc.) and want sane cancellation behavior.
-
TIL: asyncio.TaskGroup in Python 3.11+ gives you structured concurrency for free. Spin up multiple async tasks together - if one fails, the rest get cancelled automatically, and exceptions surface as a single ExceptionGroup instead of leaving orphaned tasks hanging around.
Cleaner than asyncio.gather() plus manual error juggling, especially when you're fanning out concurrent calls (DB query + external API, etc.) and want sane cancellation behavior.
-
Почему миллион корутин на Rust весит меньше, чем сто тысяч на Python
Миллион асинхронных задач на Rust спокойно живёт в нескольких сотнях мегабайт. Сто тысяч корутин на Python нередко упираются в память раньше. Дело не в том, что “Rust быстрый, а Python медленный” - дело в том, ГДЕ физически лежит состояние приостановленной задачи. Разбираю, во что превращается ваш async fn после компиляции: стейт-машина на стеке против объекта в куче. Сравниваю модели Rust (Tokio), Python (asyncio), C# и JavaScript - кто аллоцирует на каждый await, а кто нет, и почему это видно на счётчике RAM при 100k задач. Внутри: что генерирует компилятор, куда уезжает состояние между await, stackful против stackless, и что с этим делать сегодня.
https://habr.com/ru/articles/1046862/
#async #await #корутины #Rust #Tokio #asyncio #конкурентность
-
Ваши тесты медленные не из-за базы данных. Я измерил
Есть устойчивое поверье: интеграционные тесты медленные, потому что ходят в настоящую базу. «Подними SQLite в памяти», «замокай репозитории», «не гоняй Postgres в CI» — стандартный набор советов. Мокать я не люблю, но крыть упрёк «настоящая база — это медленно» было нечем. Поэтому я сел, спрофилировал и померил: 3316 интеграционных тестов, прогон 30 минут. После трёх правок инфраструктуры — 109 секунд. База оказалась ни при чём, а совет «чисти базу через TRUNCATE, это быстрее DELETE» у меня работал ровно наоборот — обидно вдвойне, потому что эта рекомендация уже лежала в черновике моей следующей статьи.
https://habr.com/ru/articles/1045923/
#pytest #pytestasyncio #интеграционные_тесты #Python #sqlalchemy #postgresql #fixtures #asyncio #cprofile #event_loop
-
Dead Letter Queue в Kafka на практике
DLQ — это просто топик. Сложное — всё, что вокруг него. Эта статья — про практическую архитектуру обработки событий из Kafka с отправкой данных во внешний REST API. Главная проблема такого сценария — нестабильность внешнего API. Он периодически деградирует по latency или начинает отвечать с ошибками, и это напрямую влияет на пропускную способность всего консьюмера.
https://habr.com/ru/articles/1045324/
#kafka #concurrency #asyncio #semaphore #finite_state_machine #dead_letter_queue #highload #api
-
Как я довёл расходы на LLM до нуля: почему на бесплатных тарифах параллелизм — враг
Это продолжение первой статьи про Briefka — там я описывал самого бота и базовую архитектуру каскада LLM-провайдеров. За прошедшие 4 месяца бот органически вырос с 59 до 84 пользователей, и именно на этом масштабе бесплатный каскад начал срываться на платного провайдера. Расскажу, почему так вышло и как я вернул расходы к нулю — с цифрами и кодом. Код ниже — реальные фрагменты из боевого Briefka, слегка сокращённые для читаемости: убраны логирование и сбор статистики.
https://habr.com/ru/articles/1044546/
#llm #ratelimit #asyncio #telegrambot #groq #deepseek #fallback #circuit_breaker
-
Топ-10 вопросов на Python backend собеседовании, которые валят джунов
Готовиться к собеседованию по списку из StackOverflow — значит знать ровно то же, что знают все остальные. Интервьюеры это чувствуют. В этой статье — 10 вопросов, которые реально задают на Python backend собеседованиях, с разбором так, как это объяснили бы вам после интервью на обратной связи.
https://habr.com/ru/articles/1044508/
#python #собеседование #junior #backend #asyncio #GIL #ORM #django #fastapi #карьера
-
Как подключить Payme к Telegram боту на Python
В этой статье разберём как подключить Payme к Telegram боту на Python используя библиотеку aiopayme — async-first решение с роутерами и dependency injection как в aiogram и FastAPI.
-
io_uring без розовых очков: 5 граблей, которые сожгли мне неделю, и где он реально быстрее epoll
io_uring продавали как убийцу epoll. На деле на HTTP keep-alive разница 0-15%, иногда не в его пользу. Но на NVMe с queue depth 128 - в 3 раза быстрее. Честный разбор с бенчмарками, реальными граблями (SQPOLL, cancel race, partial recv) и почему Google отключил io_uring в ChromeOS.
https://habr.com/ru/articles/1039820/
#io_uring #epoll #asyncio #liburing #высокаянагрузка #ядроlinux #NVMe #tokiouring #glommio #syscall
-
Learn how to use asyncio queues for efficient AI task orchestration, including pipeline design, workload optimization, and real-world examples with Redis and Python. Master asynchronous task management for scalable AI systems.
#asyncio #queues #AI task orchestration #Redis #Python
https://dasroot.net/posts/2026/02/using-asyncio-queues-ai-task-orchestration/
-
Learn how to use asyncio queues for efficient AI task orchestration, including pipeline design, workload optimization, and real-world examples with Redis and Python. Master asynchronous task management for scalable AI systems.
#asyncio #queues #AI task orchestration #Redis #Python
https://dasroot.net/posts/2026/02/using-asyncio-queues-ai-task-orchestration/
-
I am mostly known for my #Django work, but for years I have maintained #SSDP for #Python, a #UPnP substandard.
Over a month ago, I realized there isn't the an #AsyncIO library for #SIP, the #VoIP protocol.
It sent me down the deepest rabbit hole of my life. Dozens and dozens of decades-old RFC standards, some predating the Internet.
Today I emerge with a first draft and a call for HELP!
-
Python 3.4: Beyond Scripting – Building Scalable Systems
https://techlife.blog/posts/python-34-beyond-scripting
#Python #Python34 #Asyncio #Pathlib #pip #Programming #OpenSource #TheStoryOfPython
-
github-monitor is now forgewatch!
I rebranded my PR monitoring daemon. The old name locked it to a single platform, but the vision has always been broader than that. "forgewatch" better reflects what the app is really about: watching over your code forge, wherever it lives.
Why the rename? Two reasons:
1. It's more general. The architecture doesn't depend on GitHub specifically, and I want to grow it to support GitLab, Gitea, and other forges over time.
2. It's more descriptive. "forgewatch" tells you exactly what it does -- it watches your forge for pull requests and keeps you notified via D-Bus and desktop notifications on Linux.The daemon is async Python, runs as a systemd user service, and comes with an optional system tray indicator. Give it a look if you're a Linux dev who juggles PRs across repos.
https://github.com/dvoraj75/forgewatch
https://pypi.org/project/forgewatch/#forgewatch #opensource #python #linux #devtools #foss #github #gitlab #gitea #asyncio #dbus #systemd
-
Novo artigo no blog: asyncio na prática.
async/await não torna seu código automaticamente mais rápido. Se a tarefa é CPU-bound, você só adiciona complexidade sem ganho nenhum. A diferença aparece mesmo no I/O — e é dramática.
O artigo mostra os dois casos com exemplos reais, explica o event loop e quando vale (ou não) usar concorrência.
🔗 https://www.riverfount.dev.br/posts/asyncio_na_pratica/
Você já teve bug causado por uso errado de asyncio em produção?
-
Building Echobox: A Cross-Posting Service That Almost Posted Everything
https://rant.mvh.dev/building-echobox-a-cross-posting-service-that-almost-posted-everything/
#selfhosted #python #docker #mastodon #bluesky #asyncio #pixelfed #crossposting
-
The article promises an #exposé on Python's #asyncio and shared state woes but instead serves up a lukewarm brew of tech buzzwords and self-promotion. 😴💤 Spoiler alert: their "observable pattern that finally works" is as elusive as #Bigfoot. 🦄
https://www.inngest.com/blog/no-lost-updates-python-asyncio #Python #techbuzzwords #sharedstate #HackerNews #ngated -
What Python's asyncio primitives get wrong about shared state
https://www.inngest.com/blog/no-lost-updates-python-asyncio
#HackerNews #Python #asyncio #shared #state #asyncio #primitives #programming #blog
-
In asyncio Python, how would you implement the following HTTP client:
You have an initial quota of 300 HTTP requests. Every second, it gets replenished by 5, up to the maximum of 300. You can make as many requests as you want, but if your quota is exhausted, calls will block until it's been replenished. Waiting calls will get fulfilled in a FIFO fashion.
I know there's asyncio.Semaphore, but it's not designed for dynamically fluctuating limits over time.
-
@mark Hm so what would be the advantage of setting up a coroutine and leaving it to be awaited later?
I mean, not that it seems at all far-fetched that such a thing would be useful, I'm just curious since I haven't gone particularly deep into async programming and I can't think of a situation where it would be needed.
I *have* gone deep enough to understand that async functions are not just magic pixie dust though. But I love that name. Eagerly awaiting a PEP to replace the "async" keyword with "magic-pixie-dust" 😂
-
One of the funny things to me about the way we use languages with coroutines (or "async" if you're nasty) is that we set up the coroutines and then... Immediately await on them.
It's like... We're halfway there. So close. So close to actually taking advantage of concurrent programming. And yes, letting the event loop get in there instead of blocking hard on a main thread is a good thing and a strict improvement in circumstances where it matters.
But I do think sometimes about all the code I've seen where there are three network requests to three separate services that are totally independent of each other and the code is just... Eating the cost of "fully resolve request 1, fully resolve request 2, fully resolve request 3." I do wonder, sometimes, how many people think of these tools as concurrency and not just "the magic pixie-dust syntax I have to use to make half my functions the right color to be called from my other functions."
-
-
Await Is Not a Context Switch: Understanding Python's Coroutines vs. Tasks
https://mergify.com/blog/await-is-not-a-context-switch-understanding-python-s-coroutines-vs-tasks
#HackerNews #Python #Coroutines #Tasks #Asyncio #Programming #Understanding