Async python patterns

From event4u-app/agent-config · View interactive version

Async python patterns is an AI agent skill from the GitHub repository event4u-app/agent-config. When writing Python asyncio code — picking between gather / TaskGroup / wait, structured concurrency, timeouts, cancellation, sync-bridging — decision framework only, cookbook externalized.

How to use this skill

Skill file

async-python-patterns

Decision framework for picking the right Python asyncio primitive. The pattern cookbook lives upstream (links in § Provenance) — this skill is the predicate, not the recipe library. Sunset-policy compliant: the 600+ lines of language-specific cookbook stay in authoritative Python docs.

When to use

Do NOT use when:

Decision framework

Step 1 — Verify async is the right tool

Workload is:
  I/O-bound, many concurrent waits  → async fits (network, disk, IPC).
  CPU-bound (parsing, math, crypto) → async is wrong; use ProcessPoolExecutor.
  Mixed                              → async shell + run_in_executor for CPU bursts.
  Single sequential call             → don't introduce async; sync is simpler.

Step 2 — Pick the concurrency primitive

Run N independent coroutines, ALL must complete:
  Same trust level, exceptions cancel siblings  → asyncio.TaskGroup (3.11+; preferred).
  Pre-3.11 OR exceptions must NOT cancel peers  → asyncio.gather(*, return_exceptions=...).

Run N coroutines, react to results as they finish:
  → asyncio.as_completed (yields completed futures in finish order).

Run N coroutines, race to first success / failure:
  → asyncio.wait(..., return_when=FIRST_COMPLETED) + cancel pending.

Schedule fire-and-forget background work:
  → asyncio.create_task + keep a strong reference (else GC eats it).
  Forgetting the reference is the #1 silent-failure source.

Bound the wait time:
  → asyncio.wait_for(coro, timeout=...)  → raises TimeoutError on expiry.
  → asyncio.timeout(...) context manager (3.11+; preferred when many awaits share a deadline).

Bound concurrency (rate-limit, connection pool):
  → asyncio.Semaphore(n); acquire around the awaitable.

Step 3 — Bridge sync ↔ async correctly

Async code calls sync, blocking, function:
  Short pure-CPU              → fine, accept the block (microseconds).
  Long, blocking, or I/O-sync → await loop.run_in_executor(None, fn, *args).
  Library has async sibling   → switch the library (httpx vs requests, aiosqlite vs sqlite3).

Sync code calls async function:
  Top-level entrypoint        → asyncio.run(coro()).
  Inside running loop         → never asyncio.run; create_task + await it.
  Test suite                  → pytest-asyncio fixture; never raw run() in tests.

Step 4 — Cancellation discipline

Every long-running coroutine MUST be cancellation-safe:

Step 5 — Don't block the event loop

A single blocking call (sync I/O, time.sleep, CPU-heavy parse, large JSON load) freezes every coroutine. Audit every leaf function under async def:

Procedure: Apply to a new async feature

  1. Inspect the existing call graph and identify each await site, sync↔async boundary, and any blocking leaf calls before touching code.
  2. Run Step 1; reject if work is CPU-bound.
  3. Sketch the call graph; tag each await site with its primitive (Step 2).
  4. Mark every sync↔async boundary; pick the bridge per Step 3.
  5. For each long-running coroutine, write the cancel-safety contract (Step 4).
  6. Grep the leaf calls for blocking sins (Step 5); replace or push to executor.
  7. Hand the sketch to a reviewer before coding; cite this skill.

Output format

  1. Call-graph table: coroutine · concurrency primitive · timeout · cancel-safety note.
  2. Sync↔async boundary list: site · bridge · justification.
  3. Blocking-call audit: leaf function · status (async / executor / accepted-block + reason).
  4. Cancel-safety contract for each background task.

Gotcha

Do NOT

Auto-trigger keywords

Provenance

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.