AGENT SKILL

python-async

Writes and reviews correct asyncio code - structured concurrency with TaskGroup, gather vs create_task decisions, cancellation and timeout handling, bridging blocking code with to_thread, and bounded parallelism - with good/bad pairs for the pitfalls that silently freeze the event loop. Use when someone asks "why is my async code slow", "gather or create_task", "how do I run these requests concurrently", "my FastAPI endpoint blocks everything", or is converting sync Python to asyncio. Do NOT use for general pandas or data-analysis performance - use pandas-expert instead - and do NOT use for API endpoint design itself - use api-design instead.

License 许可
MIT
所属仓库
SkillMedev/skills
最近更新
2026-10-14
Stars
★ 25
Forks
3

01 前言 Front Matter

name
python-async
metadata
{ "title": "Python Async" }
description
Writes and reviews correct asyncio code - structured concurrency with TaskGroup, gather vs create_task decisions, cancellation and timeout handling, bridging blocking code with to_thread, and bounded parallelism - with good/bad pairs for the pitfalls that silently freeze the event loop. Use when someone asks "why is my async code slow", "gather or create_task", "how do I run these requests concurrently", "my FastAPI endpoint blocks everything", or is converting sync Python to asyncio. Do NOT use for general pandas or data-analysis performance - use pandas-expert instead - and do NOT use for API endpoint design itself - use api-design instead.

03 SKILL.md 正文

Python Async

Asyncio gives one thread the throughput of hundreds of connections, but only if nothing on the event loop ever blocks - a single stray time.sleep or requests.get freezes every coroutine in the process. The costly mistakes this skill prevents are the silent ones: code that runs correctly but sequentially (awaiting in a loop), tasks that vanish mid-flight (un-referenced fire-and-forget), and a "fast" service whose p99 collapses because one handler does CPU work on the loop.

Mental model

One event loop runs many coroutines cooperatively on a single thread. await is the only place control can switch; between awaits, your code has an exclusive lock on the whole process. Concurrency comes from running tasks, not from awaiting sequentially - await a(); await b() is exactly as slow as sync code.

Operating procedure

Step 1: Gather inputs

  1. Python version - 3.11+ unlocks TaskGroup and asyncio.timeout; below that, use gather and wait_for.
  2. The workload type per operation: network I/O (async-friendly), disk/blocking-library I/O (needs to_thread), or CPU-bound (needs a process pool).
  3. Every library on the I/O path, checked for an async API: httpx/aiohttp not requests, asyncpg not psycopg2, asyncio.sleep not time.sleep. If unsure whether a call blocks, treat it as blocking.
  4. The concurrency target and the downstream limits (DB pool size, API rate limits).

Step 2: Choose the concurrency primitive

  • Known, finite set of operations that should all complete or all fail together: asyncio.TaskGroup (3.11+). It cancels siblings on failure and propagates exceptions as a group - the structured default.
  • Need the list of results in order, possibly tolerating individual failures: asyncio.gather(..., return_exceptions=True), then check each result for an exception.
  • Background work that outlives the current function (consumers, listeners): asyncio.create_task, and store the reference - the loop holds tasks weakly, so an unreferenced task can be garbage-collected mid-flight. Keep a set, add a done-callback that logs exceptions and discards the task.
  • Decision rule: gather/TaskGroup when the caller waits for the results here; create_task only when the work genuinely detaches from the current scope.
import asyncio

async def main():
    async with asyncio.TaskGroup() as tg:
        t1 = tg.create_task(fetch(url1))
        t2 = tg.create_task(fetch(url2))
    # both done here; any failure cancelled the sibling and raised

asyncio.run(main())

Step 3: Bound the parallelism

Unbounded fan-out is a self-inflicted DDoS on your own database or a partner API.

  • asyncio.Semaphore(n) around the operation, with n sized to the bottleneck (e.g. DB pool size minus headroom, or the API's rate limit).
  • For pipelines, a bounded asyncio.Queue(maxsize=...) between producer and consumers - the maxsize is your backpressure.

Step 4: Keep blocking work off the loop

  • Blocking I/O (sync drivers, file reads, DNS in odd libraries): await asyncio.to_thread(blocking_fn, arg).
  • CPU-bound work (parsing, crypto, image processing): ProcessPoolExecutor via loop.run_in_executor - threads don't help CPU work under the GIL.
  • Rule of thumb: anything that could hold the loop for more than ~50ms doesn't belong on it.
  • Call async from sync only at the top level via asyncio.run; never nest event loops.

Step 5: Handle cancellation and timeouts deliberately

  • Every external await gets a timeout: async with asyncio.timeout(5): (3.11+) or asyncio.wait_for. Untimed awaits are where services hang forever.
  • Cancellation raises CancelledError at the next await point. Never swallow it - catch, clean up in try/finally, re-raise.
  • asyncio.shield only for genuinely must-finish work (e.g. committing a payment record), and sparingly - shielded work outlives its caller.

Step 6: Verify under the debug loop

Run tests with PYTHONASYNCIODEBUG=1 (or loop.set_debug(True)): it reports coroutines never awaited and callbacks that held the loop longer than 100ms - the two failure classes that are invisible in normal runs. Use async with/async for for async context managers and iterators; a bare with around an async resource leaks it.

Worked artifact: the three classic bugs, bad/good

Bad - sequential awaits masquerading as concurrency; blocking call on the loop; lost task:

async def handler(urls):
    results = []
    for u in urls:                      # runs one at a time
        results.append(await fetch(u))
    data = requests.get(META_URL)       # freezes the entire event loop
    asyncio.create_task(audit_log(data))  # unreferenced: may vanish silently
    return results

Good:

import asyncio, httpx

_background: set[asyncio.Task] = set()

def spawn(coro):
    t = asyncio.create_task(coro)
    _background.add(t)
    t.add_done_callback(lambda t: (_background.discard(t),
        t.exception() and log.error("bg task failed", exc_info=t.exception())))
    return t

async def handler(urls, client: httpx.AsyncClient):
    sem = asyncio.Semaphore(10)         # bounded fan-out
    async def bounded(u):
        async with sem:
            async with asyncio.timeout(5):
                return await fetch(client, u)
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(bounded(u)) for u in urls]
    data = await client.get(META_URL)   # async client, not requests
    spawn(audit_log(data))              # referenced, exceptions logged
    return [t.result() for t in tasks]

Deliverable

Produce working async code (or a review) in which every concurrent operation uses the right primitive with a one-line justification, every external await has a timeout, fan-out is bounded with a number tied to the downstream limit, no blocking call runs on the loop, and background tasks are referenced with exception logging.

Do NOT

  • Do not call blocking I/O (requests, time.sleep, sync DB drivers) inside a coroutine - one call stalls every request in the process.
  • Do not await in a loop when the operations are independent; that is sync code with extra syntax.
  • Do not fire-and-forget with a bare create_task - hold the reference and log its exceptions.
  • Do not swallow CancelledError; it breaks timeouts and shutdown for everything above you.
  • Do not use threads for CPU-bound work - the GIL makes that a no-op; use a process pool.
  • Do not create event loops manually or nest asyncio.run; one loop, entered once at the top.
  • Do not fan out unbounded to a database or API; size a semaphore to the real limit.

Quality bar

  • Every await on an external system sits under an explicit timeout.
  • gather vs TaskGroup vs create_task choice is justified per call site.
  • Grep for requests., time.sleep, and sync DB drivers inside async def comes back empty.
  • Concurrency bounds are numbers with a stated source, not defaults.
  • The test suite passes with PYTHONASYNCIODEBUG=1 and no slow-callback warnings.

Escalation

For the HTTP API's shape rather than its concurrency, use api-design. For rate-limit handling strategy against third parties, pair with rate-limit-handler. Queue-based cross-service pipelines belong to kafka-pipelines.

04 同仓库更多 Skills

SkillMedev
SkillMedev/skills

有氧运动计划

zone-2-cardio-plan

当有人要求制定稳态有氧训练计划、进行有氧基础训练或达到第二区间、安排轻松或耐力型的每周有氧训练、按心率区间训练,或提高静息心率、最大摄氧量或耐力时,可以使用此方案。该方案构建了一个包含训练计划结构、训练方式选择和进度安排的心率区间有氧训练模块。本方案仅提供一般健身指导,不构成医疗建议。请勿用于设计力量或举重训练计划(请使用力量训练计划)、高强度间歇训练 (HIIT) 或循环训练(请使用体能训练和 HIIT 计划),或灵活性/柔韧性训练(请使用灵活性训练计划)。

★ 25
SkillMedev
SkillMedev/skills

youtube-script-writer

Writes retention-engineered long-form YouTube scripts on a hook/body/payoff architecture - a first-30-seconds hook that survives the retention cliff, a beat-sheet body with mini-hooks and bridges, timed pattern interrupts, and a payoff that over-delivers - with B-roll and editing cues marked inline. Use when someone says "script my next video", "my retention graph dies at the start", "tighten this draft", or "outline a video on X". Do NOT use for the 3-second opener of TikTok, Reels, or Shorts - use video-hook-writer instead; do NOT use for spoken voiceover synced to on-screen tutorial actions - use narration-script instead; do NOT use for a sales demo built on a buyer's discovery notes - use demo-script instead; do NOT use to design the thumbnail and title - use thumbnail-concept instead.

★ 25
SkillMedev
SkillMedev/skills

win-back-campaign

Designs segmented win-back email sequences for dormant users - dormancy tiers, a three-beat sequence with a single proportional incentive, and a suppression rule - and measures success by re-activation, not opens. Use when someone says "our users went quiet", "design a win-back campaign", "how do I re-engage lapsed customers", "should we email people who haven't logged in for months", or lifecycle messaging has stopped landing with a lapsed segment. Do NOT use for recovering an unfinished checkout - use abandoned-cart-sequence instead. Do NOT use for diagnosing and fixing why active customers cancel - use churn-reduction instead. Do NOT use for building always-on onboarding or nurture flows - use email-drip-builder instead.

★ 25
SkillMedev
SkillMedev/skills

wikipedia-style

Writes neutral, verifiable, encyclopedic prose following Wikipedia's core content policies and manual of style - NPOV, inline citations, notability-backed claims, and a strict ban on promotional language. Use when someone asks "write this like a Wikipedia article", "draft a Wikipedia page for this company or person", "make this neutral and encyclopedic", or "why does my article draft keep getting rejected". Do NOT use for persuasive or opinion writing - use op-ed-writer instead; for thesis-driven academic papers, use academic-essay; for verifying claims in existing text, use fact-checker.

★ 25
SkillMedev
SkillMedev/skills

whitepapers

Structures and writes authoritative B2B whitepapers - a standalone executive summary, a data-sized problem statement, methodology, evidence-driven findings, recommendations, and a soft call to action - flagging every claim that needs a real citation. Use when a marketer asks "write a whitepaper on this topic", "turn our research into a lead-gen asset", "make this credible enough for executives", or a draft reads like a product pitch instead of analysis. Do NOT use for customer-story-driven proof - use case-study-builder instead; for policy audiences, use policy-brief.

★ 25
SkillMedev
SkillMedev/skills

white-space-analysis

Finds unmet market gaps by ranking jobs-to-be-done on importance versus satisfaction, overlaying them against current solutions and workarounds, and validating that each gap is real, winnable, and worth winning. Use when someone asks "where are the gaps in this market", "what's underserved here", "where should we play next", or is hunting for product, feature, or market-entry opportunities. Do NOT use for profiling competitors and building battle cards - use competitive-intelligence instead; for putting a dollar figure on an identified opportunity - use market-sizing instead; for extracting jobs-to-be-done from raw customer interviews - use jtbd-extractor instead.

★ 25