python-async-patterns
Async Python patterns for non-blocking I/O with asyncio: TaskGroup, cancellation, timeouts, backpressure, rate limiting, and safe sync/async boundaries. Use when implementing concurrent network/DB workflows or async services — not for thread/process GIL tuning (python-performance) or general Python
v2026.11.13-21cd5683 установки+3 за 7 дней39 ЗвездыMITсинхронизировано 10 часов назад
Установка
Ещё нет NotHoly CLI? Сначала установите её.
$ curl -fsSL https://notholy.com/install.sh | sh$ notholy skills install aeondave/python-async-patternsПишет в ~/.notholy/skills после проверки подписи и SHA-256.
ПодписьПодписано, ed25519
Пакетf0f17967…a761dfd9
f0f17967d51f…5977a761dfd96 файлов · 5.6 KBПроверкаНизкий1 замечание
- Ссылки на внешние домены
Источникgithub.com/AeonDave/malskill/tree/main/coding/python-async-patterns@21cd568
Эта запись еще не переведена на русский, поэтому показан текст на другом языке: English.
На странице
This skill focuses on practical asyncio patterns for I/O-bound concurrency.
Thread/process/subinterpreter parallelism and the GIL are python-performance / python-patterns concurrency.md.
When to activate
- You’re building an async service/client (HTTP, DB, queues, websockets)
- You need concurrency with limits (rate limiting, semaphores)
- You need safe cancellation and timeouts
- You suspect event loop blocking (sync call inside async path)
- A task is stuck: 3.14+ call-graph /
python -m asyncio pstree
Rules of engagement
- Prefer async only for I/O-bound workloads.
- Never block the event loop (no
time.sleep(), no sync HTTP/DB in async code). - Make cancellation and timeouts explicit.
- Bound concurrency; unbounded
gather()can turn memory into a queue. asyncio.CancelledErroris aBaseException.except Exceptionwill not see it. Cleanup, then re-raise.- Do not call
asyncio.get_event_loop()to create work. From sync code useasyncio.run()(orasyncio.Runner3.11+). Inside async code useget_running_loop()only when you must.
Outcome expectations
- Concurrent I/O tasks are orchestrated with clear boundaries and failure semantics.
- Cancellation and timeouts are explicit and tested.
- Event loop is never blocked by sync calls; backpressure prevents unbounded growth.
Recommended workflow
- Define scope and concurrency bounds before writing async code.
- Use TaskGroup for orchestration; avoid fire-and-forget
create_task. - Apply timeouts at I/O boundaries, not broad scopes.
- Test cancellation paths; use pytest-asyncio with function-scoped loops.
- Profile event loop blocking; offload sync work via
to_thread()when necessary.
Quick patterns
Concurrent fan-out with bounds (TaskGroup preferred)
Prefer asyncio.TaskGroup (Python 3.11+) for structured concurrency with clear failure propagation.
async with asyncio.TaskGroup() as tg:
tg.create_task(fetch_url(url1))
tg.create_task(fetch_url(url2))
# All tasks joined; exceptions aggregated as ExceptionGroupFor concurrency limits, add a semaphore:
sem = asyncio.Semaphore(10)
async def bounded():
async with sem:
return await fetch_url(url)Timeouts
- Prefer
asyncio.timeout()(3.11+) for scoped timeouts. On expiry it raisesTimeoutError(builtin).asyncio.TimeoutErroris a 3.11+ alias of that builtin — preferTimeoutError. asyncio.timeout(None)means no timeout.
Cancellation
task.cancel()is not awaitable; it returnsbool(False if already done). Thenawait taskand handleCancelledError.- Catch
CancelledErroronly to clean up, then re-raise.
Sync/async boundary
- Offload truly blocking work via
asyncio.to_thread().
Resources
Load on demand:
references/foundations.md— event loop, coroutines vs tasks, TaskGroup vs gather, 3.12 eager tasks, 3.14 call graphsreferences/cancellation-timeouts.md—cancel()/CancelledError/timeout/uncancelreferences/backpressure-rate-limit.md— queues (QueueShutDown3.13+), semaphores, producer/consumer, rate limitingreferences/sync-async-interop.md—to_thread, executors, free-threaded loops (3.14)references/testing.md— pytest-asyncio and cancellation tests (pair withpython-testing)
Файлы этой версии
references/510.8 KB
- backpressure-rate-limit.md1.3 KB
- cancellation-timeouts.md2.7 KB
- foundations.md3.6 KB
- sync-async-interop.md1.3 KB
- testing.md2.0 KB
- SKILL.md3.9 KB
Права
| Право | Заявлено | Найдено проверкой |
|---|---|---|
| Читает файлы | Нет | Нет |
| Пишет файлы | Нет | Нет |
| Выполняет команды shell | Нет | Нет |
| Ходит в сеть | Да | Да |
| Использует коннекторы | Нет | Нет |
| Управляет браузером | Нет | Нет |
Замечания проверки
Проверено 13 нояб. 2026 г.
- ИнфоСсылка · Ссылки на внешние домены
Чистая проверка снижает риск, но не доказывает, что пакет безопасен. Читайте то, что ставите.
| Версия | Опубликована | Коммит | SHA-256 | Подпись | Изменение прав |
|---|---|---|---|---|---|
| v2026.11.13-21cd568 | 13 нояб. 2026 г. | 21cd568 | f0f17967 | Подписана | – |
Ещё от AeonDave
Всё от этого издателяЕще в категории «Сети, беспроводная связь и телеком»
Вся категория- performing-network-packet-capture-analysismukul975/performing-network-packet-capture-analysis4
- network-segmentation-reviewsecurityskills/network-segmentation-review3
- performing-ssl-stripping-attackmukul975/performing-ssl-stripping-attack3
- implementing-next-generation-firewall-with-palo-altomukul975/implementing-next-generation-firewall-with-palo-alto3
- configuring-zscaler-private-access-for-ztnamukul975/configuring-zscaler-private-access-for-ztna3
- implementing-canary-tokens-for-network-intrusionmukul975/implementing-canary-tokens-for-network-intrusion3
Спрашивайте обо всём, что позволяет ваш скоуп.
Создайте аккаунт, пополните баланс и задайте первый вопрос в чате или в терминале.
- 1/3
Создайте аккаунт
Личный или для компании. Позже можно перейти на аккаунт компании без потери баланса и ключей.
ЛичныйКомпания - 2/3
Пополните баланс
Картой. Оплата за токены, без подписки.
$5.00минимальное пополнение - 3/3
Спрашивайте
В чате, или установите CLI и выполните notholy login в терминале.
$ notholy login