[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M70GH83E14CF7P54QSA1VPNJ":3,"skill-same:01M70GH83E14CF7P54QSA1VPNJ":71},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":23,"publishedAt":42,"linkOnly":43,"markdownContent":44,"markdownBody":45,"frontMatter":46,"refName":47,"commitSha":48,"skillDirectory":49,"forksCount":50,"repositoryHtmlUrl":51,"repositoryHomepageUrl":52,"ownerHtmlUrl":53,"ownerBlogUrl":54,"ownerDescription":55,"updatedAt":56,"install":57,"resources":70},"01M70GH83E14CF7P54QSA1VPNJ","async-python-patterns",null,"Master Python asyncio, concurrent programming, and async\u002Fawait patterns for high-performance applications. Use when building async APIs, concurrent systems, or I\u002FO-bound applications requiring non-blocking operations.","shengdabai\u002FTony-Claude-Code-Skills","shengdabai","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F116417419?v=4","01M70F6D2WY5PQV5A92BKYJQEW","Tony Sheng","01M70F6D3GAAAYZ5H4CC1G8VXM",3,"MIT","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002F_collections\u002Fplugins\u002Fpython-development\u002Fskills\u002Fasync-python-patterns\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41],"async python patterns","async","python","python patterns","patterns","systems","operations","high","programming","use","applications","for","asyncio","await","master","when","high-performance","performance","2026-11-10 10:12:30",false,"---\nname: async-python-patterns\ndescription: Master Python asyncio, concurrent programming, and async\u002Fawait patterns for high-performance applications. Use when building async APIs, concurrent systems, or I\u002FO-bound applications requiring non-blocking operations.\n---\n\n# Async Python Patterns\n\nComprehensive guidance for implementing asynchronous Python applications using asyncio, concurrent programming patterns, and async\u002Fawait for building high-performance, non-blocking systems.\n\n## When to Use This Skill\n\n- Building async web APIs (FastAPI, aiohttp, Sanic)\n- Implementing concurrent I\u002FO operations (database, file, network)\n- Creating web scrapers with concurrent requests\n- Developing real-time applications (WebSocket servers, chat systems)\n- Processing multiple independent tasks simultaneously\n- Building microservices with async communication\n- Optimizing I\u002FO-bound workloads\n- Implementing async background tasks and queues\n\n## Core Concepts\n\n### 1. Event Loop\nThe event loop is the heart of asyncio, managing and scheduling asynchronous tasks.\n\n**Key characteristics:**\n- Single-threaded cooperative multitasking\n- Schedules coroutines for execution\n- Handles I\u002FO operations without blocking\n- Manages callbacks and futures\n\n### 2. Coroutines\nFunctions defined with `async def` that can be paused and resumed.\n\n**Syntax:**\n```python\nasync def my_coroutine():\n    result = await some_async_operation()\n    return result\n```\n\n### 3. Tasks\nScheduled coroutines that run concurrently on the event loop.\n\n### 4. Futures\nLow-level objects representing eventual results of async operations.\n\n### 5. Async Context Managers\nResources that support `async with` for proper cleanup.\n\n### 6. Async Iterators\nObjects that support `async for` for iterating over async data sources.\n\n## Quick Start\n\n```python\nimport asyncio\n\nasync def main():\n    print(\"Hello\")\n    await asyncio.sleep(1)\n    print(\"World\")\n\n# Python 3.7+\nasyncio.run(main())\n```\n\n## Fundamental Patterns\n\n### Pattern 1: Basic Async\u002FAwait\n\n```python\nimport asyncio\n\nasync def fetch_data(url: str) -> dict:\n    \"\"\"Fetch data from URL asynchronously.\"\"\"\n    await asyncio.sleep(1)  # Simulate I\u002FO\n    return {\"url\": url, \"data\": \"result\"}\n\nasync def main():\n    result = await fetch_data(\"https:\u002F\u002Fapi.example.com\")\n    print(result)\n\nasyncio.run(main())\n```\n\n### Pattern 2: Concurrent Execution with gather()\n\n```python\nimport asyncio\nfrom typing import List\n\nasync def fetch_user(user_id: int) -> dict:\n    \"\"\"Fetch user data.\"\"\"\n    await asyncio.sleep(0.5)\n    return {\"id\": user_id, \"name\": f\"User {user_id}\"}\n\nasync def fetch_all_users(user_ids: List[int]) -> List[dict]:\n    \"\"\"Fetch multiple users concurrently.\"\"\"\n    tasks = [fetch_user(uid) for uid in user_ids]\n    results = await asyncio.gather(*tasks)\n    return results\n\nasync def main():\n    user_ids = [1, 2, 3, 4, 5]\n    users = await fetch_all_users(user_ids)\n    print(f\"Fetched {len(users)} users\")\n\nasyncio.run(main())\n```\n\n### Pattern 3: Task Creation and Management\n\n```python\nimport asyncio\n\nasync def background_task(name: str, delay: int):\n    \"\"\"Long-running background task.\"\"\"\n    print(f\"{name} started\")\n    await asyncio.sleep(delay)\n    print(f\"{name} completed\")\n    return f\"Result from {name}\"\n\nasync def main():\n    # Create tasks\n    task1 = asyncio.create_task(background_task(\"Task 1\", 2))\n    task2 = asyncio.create_task(background_task(\"Task 2\", 1))\n\n    # Do other work\n    print(\"Main: doing other work\")\n    await asyncio.sleep(0.5)\n\n    # Wait for tasks\n    result1 = await task1\n    result2 = await task2\n\n    print(f\"Results: {result1}, {result2}\")\n\nasyncio.run(main())\n```\n\n### Pattern 4: Error Handling in Async Code\n\n```python\nimport asyncio\nfrom typing import List, Optional\n\nasync def risky_operation(item_id: int) -> dict:\n    \"\"\"Operation that might fail.\"\"\"\n    await asyncio.sleep(0.1)\n    if item_id % 3 == 0:\n        raise ValueError(f\"Item {item_id} failed\")\n    return {\"id\": item_id, \"status\": \"success\"}\n\nasync def safe_operation(item_id: int) -> Optional[dict]:\n    \"\"\"Wrapper with error handling.\"\"\"\n    try:\n        return await risky_operation(item_id)\n    except ValueError as e:\n        print(f\"Error: {e}\")\n        return None\n\nasync def process_items(item_ids: List[int]):\n    \"\"\"Process multiple items with error handling.\"\"\"\n    tasks = [safe_operation(iid) for iid in item_ids]\n    results = await asyncio.gather(*tasks, return_exceptions=True)\n\n    # Filter out failures\n    successful = [r for r in results if r is not None and not isinstance(r, Exception)]\n    failed = [r for r in results if isinstance(r, Exception)]\n\n    print(f\"Success: {len(successful)}, Failed: {len(failed)}\")\n    return successful\n\nasyncio.run(process_items([1, 2, 3, 4, 5, 6]))\n```\n\n### Pattern 5: Timeout Handling\n\n```python\nimport asyncio\n\nasync def slow_operation(delay: int) -> str:\n    \"\"\"Operation that takes time.\"\"\"\n    await asyncio.sleep(delay)\n    return f\"Completed after {delay}s\"\n\nasync def with_timeout():\n    \"\"\"Execute operation with timeout.\"\"\"\n    try:\n        result = await asyncio.wait_for(slow_operation(5), timeout=2.0)\n        print(result)\n    except asyncio.TimeoutError:\n        print(\"Operation timed out\")\n\nasyncio.run(with_timeout())\n```\n\n## Advanced Patterns\n\n### Pattern 6: Async Context Managers\n\n```python\nimport asyncio\nfrom typing import Optional\n\nclass AsyncDatabaseConnection:\n    \"\"\"Async database connection context manager.\"\"\"\n\n    def __init__(self, dsn: str):\n        self.dsn = dsn\n        self.connection: Optional[object] = None\n\n    async def __aenter__(self):\n        print(\"Opening connection\")\n        await asyncio.sleep(0.1)  # Simulate connection\n        self.connection = {\"dsn\": self.dsn, \"connected\": True}\n        return self.connection\n\n    async def __aexit__(self, exc_type, exc_val, exc_tb):\n        print(\"Closing connection\")\n        await asyncio.sleep(0.1)  # Simulate cleanup\n        self.connection = None\n\nasync def query_database():\n    \"\"\"Use async context manager.\"\"\"\n    async with AsyncDatabaseConnection(\"postgresql:\u002F\u002Flocalhost\") as conn:\n        print(f\"Using connection: {conn}\")\n        await asyncio.sleep(0.2)  # Simulate query\n        return {\"rows\": 10}\n\nasyncio.run(query_database())\n```\n\n### Pattern 7: Async Iterators and Generators\n\n```python\nimport asyncio\nfrom typing import AsyncIterator\n\nasync def async_range(start: int, end: int, delay: float = 0.1) -> AsyncIterator[int]:\n    \"\"\"Async generator that yields numbers with delay.\"\"\"\n    for i in range(start, end):\n        await asyncio.sleep(delay)\n        yield i\n\nasync def fetch_pages(url: str, max_pages: int) -> AsyncIterator[dict]:\n    \"\"\"Fetch paginated data asynchronously.\"\"\"\n    for page in range(1, max_pages + 1):\n        await asyncio.sleep(0.2)  # Simulate API call\n        yield {\n            \"page\": page,\n            \"url\": f\"{url}?page={page}\",\n            \"data\": [f\"item_{page}_{i}\" for i in range(5)]\n        }\n\nasync def consume_async_iterator():\n    \"\"\"Consume async iterator.\"\"\"\n    async for number in async_range(1, 5):\n        print(f\"Number: {number}\")\n\n    print(\"\\nFetching pages:\")\n    async for page_data in fetch_pages(\"https:\u002F\u002Fapi.example.com\u002Fitems\", 3):\n        print(f\"Page {page_data['page']}: {len(page_data['data'])} items\")\n\nasyncio.run(consume_async_iterator())\n```\n\n### Pattern 8: Producer-Consumer Pattern\n\n```python\nimport asyncio\nfrom asyncio import Queue\nfrom typing import Optional\n\nasync def producer(queue: Queue, producer_id: int, num_items: int):\n    \"\"\"Produce items and put them in queue.\"\"\"\n    for i in range(num_items):\n        item = f\"Item-{producer_id}-{i}\"\n        await queue.put(item)\n        print(f\"Producer {producer_id} produced: {item}\")\n        await asyncio.sleep(0.1)\n    await queue.put(None)  # Signal completion\n\nasync def consumer(queue: Queue, consumer_id: int):\n    \"\"\"Consume items from queue.\"\"\"\n    while True:\n        item = await queue.get()\n        if item is None:\n            queue.task_done()\n            break\n\n        print(f\"Consumer {consumer_id} processing: {item}\")\n        await asyncio.sleep(0.2)  # Simulate work\n        queue.task_done()\n\nasync def producer_consumer_example():\n    \"\"\"Run producer-consumer pattern.\"\"\"\n    queue = Queue(maxsize=10)\n\n    # Create tasks\n    producers = [\n        asyncio.create_task(producer(queue, i, 5))\n        for i in range(2)\n    ]\n\n    consumers = [\n        asyncio.create_task(consumer(queue, i))\n        for i in range(3)\n    ]\n\n    # Wait for producers\n    await asyncio.gather(*producers)\n\n    # Wait for queue to be empty\n    await queue.join()\n\n    # Cancel consumers\n    for c in consumers:\n        c.cancel()\n\nasyncio.run(producer_consumer_example())\n```\n\n### Pattern 9: Semaphore for Rate Limiting\n\n```python\nimport asyncio\nfrom typing import List\n\nasync def api_call(url: str, semaphore: asyncio.Semaphore) -> dict:\n    \"\"\"Make API call with rate limiting.\"\"\"\n    async with semaphore:\n        print(f\"Calling {url}\")\n        await asyncio.sleep(0.5)  # Simulate API call\n        return {\"url\": url, \"status\": 200}\n\nasync def rate_limited_requests(urls: List[str], max_concurrent: int = 5):\n    \"\"\"Make multiple requests with rate limiting.\"\"\"\n    semaphore = asyncio.Semaphore(max_concurrent)\n    tasks = [api_call(url, semaphore) for url in urls]\n    results = await asyncio.gather(*tasks)\n    return results\n\nasync def main():\n    urls = [f\"https:\u002F\u002Fapi.example.com\u002Fitem\u002F{i}\" for i in range(20)]\n    results = await rate_limited_requests(urls, max_concurrent=3)\n    print(f\"Completed {len(results)} requests\")\n\nasyncio.run(main())\n```\n\n### Pattern 10: Async Locks and Synchronization\n\n```python\nimport asyncio\n\nclass AsyncCounter:\n    \"\"\"Thread-safe async counter.\"\"\"\n\n    def __init__(self):\n        self.value = 0\n        self.lock = asyncio.Lock()\n\n    async def increment(self):\n        \"\"\"Safely increment counter.\"\"\"\n        async with self.lock:\n            current = self.value\n            await asyncio.sleep(0.01)  # Simulate work\n            self.value = current + 1\n\n    async def get_value(self) -> int:\n        \"\"\"Get current value.\"\"\"\n        async with self.lock:\n            return self.value\n\nasync def worker(counter: AsyncCounter, worker_id: int):\n    \"\"\"Worker that increments counter.\"\"\"\n    for _ in range(10):\n        await counter.increment()\n        print(f\"Worker {worker_id} incremented\")\n\nasync def test_counter():\n    \"\"\"Test concurrent counter.\"\"\"\n    counter = AsyncCounter()\n\n    workers = [asyncio.create_task(worker(counter, i)) for i in range(5)]\n    await asyncio.gather(*workers)\n\n    final_value = await counter.get_value()\n    print(f\"Final counter value: {final_value}\")\n\nasyncio.run(test_counter())\n```\n\n## Real-World Applications\n\n### Web Scraping with aiohttp\n\n```python\nimport asyncio\nimport aiohttp\nfrom typing import List, Dict\n\nasync def fetch_url(session: aiohttp.ClientSession, url: str) -> Dict:\n    \"\"\"Fetch single URL.\"\"\"\n    try:\n        async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as response:\n            text = await response.text()\n            return {\n                \"url\": url,\n                \"status\": response.status,\n                \"length\": len(text)\n            }\n    except Exception as e:\n        return {\"url\": url, \"error\": str(e)}\n\nasync def scrape_urls(urls: List[str]) -> List[Dict]:\n    \"\"\"Scrape multiple URLs concurrently.\"\"\"\n    async with aiohttp.ClientSession() as session:\n        tasks = [fetch_url(session, url) for url in urls]\n        results = await asyncio.gather(*tasks)\n        return results\n\nasync def main():\n    urls = [\n        \"https:\u002F\u002Fhttpbin.org\u002Fdelay\u002F1\",\n        \"https:\u002F\u002Fhttpbin.org\u002Fdelay\u002F2\",\n        \"https:\u002F\u002Fhttpbin.org\u002Fstatus\u002F404\",\n    ]\n\n    results = await scrape_urls(urls)\n    for result in results:\n        print(result)\n\nasyncio.run(main())\n```\n\n### Async Database Operations\n\n```python\nimport asyncio\nfrom typing import List, Optional\n\n# Simulated async database client\nclass AsyncDB:\n    \"\"\"Simulated async database.\"\"\"\n\n    async def execute(self, query: str) -> List[dict]:\n        \"\"\"Execute query.\"\"\"\n        await asyncio.sleep(0.1)\n        return [{\"id\": 1, \"name\": \"Example\"}]\n\n    async def fetch_one(self, query: str) -> Optional[dict]:\n        \"\"\"Fetch single row.\"\"\"\n        await asyncio.sleep(0.1)\n        return {\"id\": 1, \"name\": \"Example\"}\n\nasync def get_user_data(db: AsyncDB, user_id: int) -> dict:\n    \"\"\"Fetch user and related data concurrently.\"\"\"\n    user_task = db.fetch_one(f\"SELECT * FROM users WHERE id = {user_id}\")\n    orders_task = db.execute(f\"SELECT * FROM orders WHERE user_id = {user_id}\")\n    profile_task = db.fetch_one(f\"SELECT * FROM profiles WHERE user_id = {user_id}\")\n\n    user, orders, profile = await asyncio.gather(user_task, orders_task, profile_task)\n\n    return {\n        \"user\": user,\n        \"orders\": orders,\n        \"profile\": profile\n    }\n\nasync def main():\n    db = AsyncDB()\n    user_data = await get_user_data(db, 1)\n    print(user_data)\n\nasyncio.run(main())\n```\n\n### WebSocket Server\n\n```python\nimport asyncio\nfrom typing import Set\n\n# Simulated WebSocket connection\nclass WebSocket:\n    \"\"\"Simulated WebSocket.\"\"\"\n\n    def __init__(self, client_id: str):\n        self.client_id = client_id\n\n    async def send(self, message: str):\n        \"\"\"Send message.\"\"\"\n        print(f\"Sending to {self.client_id}: {message}\")\n        await asyncio.sleep(0.01)\n\n    async def recv(self) -> str:\n        \"\"\"Receive message.\"\"\"\n        await asyncio.sleep(1)\n        return f\"Message from {self.client_id}\"\n\nclass WebSocketServer:\n    \"\"\"Simple WebSocket server.\"\"\"\n\n    def __init__(self):\n        self.clients: Set[WebSocket] = set()\n\n    async def register(self, websocket: WebSocket):\n        \"\"\"Register new client.\"\"\"\n        self.clients.add(websocket)\n        print(f\"Client {websocket.client_id} connected\")\n\n    async def unregister(self, websocket: WebSocket):\n        \"\"\"Unregister client.\"\"\"\n        self.clients.remove(websocket)\n        print(f\"Client {websocket.client_id} disconnected\")\n\n    async def broadcast(self, message: str):\n        \"\"\"Broadcast message to all clients.\"\"\"\n        if self.clients:\n            tasks = [client.send(message) for client in self.clients]\n            await asyncio.gather(*tasks)\n\n    async def handle_client(self, websocket: WebSocket):\n        \"\"\"Handle individual client connection.\"\"\"\n        await self.register(websocket)\n        try:\n            async for message in self.message_iterator(websocket):\n                await self.broadcast(f\"{websocket.client_id}: {message}\")\n        finally:\n            await self.unregister(websocket)\n\n    async def message_iterator(self, websocket: WebSocket):\n        \"\"\"Iterate over messages from client.\"\"\"\n        for _ in range(3):  # Simulate 3 messages\n            yield await websocket.recv()\n```\n\n## Performance Best Practices\n\n### 1. Use Connection Pools\n\n```python\nimport asyncio\nimport aiohttp\n\nasync def with_connection_pool():\n    \"\"\"Use connection pool for efficiency.\"\"\"\n    connector = aiohttp.TCPConnector(limit=100, limit_per_host=10)\n\n    async with aiohttp.ClientSession(connector=connector) as session:\n        tasks = [session.get(f\"https:\u002F\u002Fapi.example.com\u002Fitem\u002F{i}\") for i in range(50)]\n        responses = await asyncio.gather(*tasks)\n        return responses\n```\n\n### 2. Batch Operations\n\n```python\nasync def batch_process(items: List[str], batch_size: int = 10):\n    \"\"\"Process items in batches.\"\"\"\n    for i in range(0, len(items), batch_size):\n        batch = items[i:i + batch_size]\n        tasks = [process_item(item) for item in batch]\n        await asyncio.gather(*tasks)\n        print(f\"Processed batch {i \u002F\u002F batch_size + 1}\")\n\nasync def process_item(item: str):\n    \"\"\"Process single item.\"\"\"\n    await asyncio.sleep(0.1)\n    return f\"Processed: {item}\"\n```\n\n### 3. Avoid Blocking Operations\n\n```python\nimport asyncio\nimport concurrent.futures\nfrom typing import Any\n\ndef blocking_operation(data: Any) -> Any:\n    \"\"\"CPU-intensive blocking operation.\"\"\"\n    import time\n    time.sleep(1)\n    return data * 2\n\nasync def run_in_executor(data: Any) -> Any:\n    \"\"\"Run blocking operation in thread pool.\"\"\"\n    loop = asyncio.get_event_loop()\n    with concurrent.futures.ThreadPoolExecutor() as pool:\n        result = await loop.run_in_executor(pool, blocking_operation, data)\n        return result\n\nasync def main():\n    results = await asyncio.gather(*[run_in_executor(i) for i in range(5)])\n    print(results)\n\nasyncio.run(main())\n```\n\n## Common Pitfalls\n\n### 1. Forgetting await\n\n```python\n# Wrong - returns coroutine object, doesn't execute\nresult = async_function()\n\n# Correct\nresult = await async_function()\n```\n\n### 2. Blocking the Event Loop\n\n```python\n# Wrong - blocks event loop\nimport time\nasync def bad():\n    time.sleep(1)  # Blocks!\n\n# Correct\nasync def good():\n    await asyncio.sleep(1)  # Non-blocking\n```\n\n### 3. Not Handling Cancellation\n\n```python\nasync def cancelable_task():\n    \"\"\"Task that handles cancellation.\"\"\"\n    try:\n        while True:\n            await asyncio.sleep(1)\n            print(\"Working...\")\n    except asyncio.CancelledError:\n        print(\"Task cancelled, cleaning up...\")\n        # Perform cleanup\n        raise  # Re-raise to propagate cancellation\n```\n\n### 4. Mixing Sync and Async Code\n\n```python\n# Wrong - can't call async from sync directly\ndef sync_function():\n    result = await async_function()  # SyntaxError!\n\n# Correct\ndef sync_function():\n    result = asyncio.run(async_function())\n```\n\n## Testing Async Code\n\n```python\nimport asyncio\nimport pytest\n\n# Using pytest-asyncio\n@pytest.mark.asyncio\nasync def test_async_function():\n    \"\"\"Test async function.\"\"\"\n    result = await fetch_data(\"https:\u002F\u002Fapi.example.com\")\n    assert result is not None\n\n@pytest.mark.asyncio\nasync def test_with_timeout():\n    \"\"\"Test with timeout.\"\"\"\n    with pytest.raises(asyncio.TimeoutError):\n        await asyncio.wait_for(slow_operation(5), timeout=1.0)\n```\n\n## Resources\n\n- **Python asyncio documentation**: https:\u002F\u002Fdocs.python.org\u002F3\u002Flibrary\u002Fasyncio.html\n- **aiohttp**: Async HTTP client\u002Fserver\n- **FastAPI**: Modern async web framework\n- **asyncpg**: Async PostgreSQL driver\n- **motor**: Async MongoDB driver\n\n## Best Practices Summary\n\n1. **Use asyncio.run()** for entry point (Python 3.7+)\n2. **Always await coroutines** to execute them\n3. **Use gather() for concurrent execution** of multiple tasks\n4. **Implement proper error handling** with try\u002Fexcept\n5. **Use timeouts** to prevent hanging operations\n6. **Pool connections** for better performance\n7. **Avoid blocking operations** in async code\n8. **Use semaphores** for rate limiting\n9. **Handle task cancellation** properly\n10. **Test async code** with pytest-asyncio\n","# Async Python Patterns\n\nComprehensive guidance for implementing asynchronous Python applications using asyncio, concurrent programming patterns, and async\u002Fawait for building high-performance, non-blocking systems.\n\n## When to Use This Skill\n\n- Building async web APIs (FastAPI, aiohttp, Sanic)\n- Implementing concurrent I\u002FO operations (database, file, network)\n- Creating web scrapers with concurrent requests\n- Developing real-time applications (WebSocket servers, chat systems)\n- Processing multiple independent tasks simultaneously\n- Building microservices with async communication\n- Optimizing I\u002FO-bound workloads\n- Implementing async background tasks and queues\n\n## Core Concepts\n\n### 1. Event Loop\nThe event loop is the heart of asyncio, managing and scheduling asynchronous tasks.\n\n**Key characteristics:**\n- Single-threaded cooperative multitasking\n- Schedules coroutines for execution\n- Handles I\u002FO operations without blocking\n- Manages callbacks and futures\n\n### 2. Coroutines\nFunctions defined with `async def` that can be paused and resumed.\n\n**Syntax:**\n```python\nasync def my_coroutine():\n    result = await some_async_operation()\n    return result\n```\n\n### 3. Tasks\nScheduled coroutines that run concurrently on the event loop.\n\n### 4. Futures\nLow-level objects representing eventual results of async operations.\n\n### 5. Async Context Managers\nResources that support `async with` for proper cleanup.\n\n### 6. Async Iterators\nObjects that support `async for` for iterating over async data sources.\n\n## Quick Start\n\n```python\nimport asyncio\n\nasync def main():\n    print(\"Hello\")\n    await asyncio.sleep(1)\n    print(\"World\")\n\n# Python 3.7+\nasyncio.run(main())\n```\n\n## Fundamental Patterns\n\n### Pattern 1: Basic Async\u002FAwait\n\n```python\nimport asyncio\n\nasync def fetch_data(url: str) -> dict:\n    \"\"\"Fetch data from URL asynchronously.\"\"\"\n    await asyncio.sleep(1)  # Simulate I\u002FO\n    return {\"url\": url, \"data\": \"result\"}\n\nasync def main():\n    result = await fetch_data(\"https:\u002F\u002Fapi.example.com\")\n    print(result)\n\nasyncio.run(main())\n```\n\n### Pattern 2: Concurrent Execution with gather()\n\n```python\nimport asyncio\nfrom typing import List\n\nasync def fetch_user(user_id: int) -> dict:\n    \"\"\"Fetch user data.\"\"\"\n    await asyncio.sleep(0.5)\n    return {\"id\": user_id, \"name\": f\"User {user_id}\"}\n\nasync def fetch_all_users(user_ids: List[int]) -> List[dict]:\n    \"\"\"Fetch multiple users concurrently.\"\"\"\n    tasks = [fetch_user(uid) for uid in user_ids]\n    results = await asyncio.gather(*tasks)\n    return results\n\nasync def main():\n    user_ids = [1, 2, 3, 4, 5]\n    users = await fetch_all_users(user_ids)\n    print(f\"Fetched {len(users)} users\")\n\nasyncio.run(main())\n```\n\n### Pattern 3: Task Creation and Management\n\n```python\nimport asyncio\n\nasync def background_task(name: str, delay: int):\n    \"\"\"Long-running background task.\"\"\"\n    print(f\"{name} started\")\n    await asyncio.sleep(delay)\n    print(f\"{name} completed\")\n    return f\"Result from {name}\"\n\nasync def main():\n    # Create tasks\n    task1 = asyncio.create_task(background_task(\"Task 1\", 2))\n    task2 = asyncio.create_task(background_task(\"Task 2\", 1))\n\n    # Do other work\n    print(\"Main: doing other work\")\n    await asyncio.sleep(0.5)\n\n    # Wait for tasks\n    result1 = await task1\n    result2 = await task2\n\n    print(f\"Results: {result1}, {result2}\")\n\nasyncio.run(main())\n```\n\n### Pattern 4: Error Handling in Async Code\n\n```python\nimport asyncio\nfrom typing import List, Optional\n\nasync def risky_operation(item_id: int) -> dict:\n    \"\"\"Operation that might fail.\"\"\"\n    await asyncio.sleep(0.1)\n    if item_id % 3 == 0:\n        raise ValueError(f\"Item {item_id} failed\")\n    return {\"id\": item_id, \"status\": \"success\"}\n\nasync def safe_operation(item_id: int) -> Optional[dict]:\n    \"\"\"Wrapper with error handling.\"\"\"\n    try:\n        return await risky_operation(item_id)\n    except ValueError as e:\n        print(f\"Error: {e}\")\n        return None\n\nasync def process_items(item_ids: List[int]):\n    \"\"\"Process multiple items with error handling.\"\"\"\n    tasks = [safe_operation(iid) for iid in item_ids]\n    results = await asyncio.gather(*tasks, return_exceptions=True)\n\n    # Filter out failures\n    successful = [r for r in results if r is not None and not isinstance(r, Exception)]\n    failed = [r for r in results if isinstance(r, Exception)]\n\n    print(f\"Success: {len(successful)}, Failed: {len(failed)}\")\n    return successful\n\nasyncio.run(process_items([1, 2, 3, 4, 5, 6]))\n```\n\n### Pattern 5: Timeout Handling\n\n```python\nimport asyncio\n\nasync def slow_operation(delay: int) -> str:\n    \"\"\"Operation that takes time.\"\"\"\n    await asyncio.sleep(delay)\n    return f\"Completed after {delay}s\"\n\nasync def with_timeout():\n    \"\"\"Execute operation with timeout.\"\"\"\n    try:\n        result = await asyncio.wait_for(slow_operation(5), timeout=2.0)\n        print(result)\n    except asyncio.TimeoutError:\n        print(\"Operation timed out\")\n\nasyncio.run(with_timeout())\n```\n\n## Advanced Patterns\n\n### Pattern 6: Async Context Managers\n\n```python\nimport asyncio\nfrom typing import Optional\n\nclass AsyncDatabaseConnection:\n    \"\"\"Async database connection context manager.\"\"\"\n\n    def __init__(self, dsn: str):\n        self.dsn = dsn\n        self.connection: Optional[object] = None\n\n    async def __aenter__(self):\n        print(\"Opening connection\")\n        await asyncio.sleep(0.1)  # Simulate connection\n        self.connection = {\"dsn\": self.dsn, \"connected\": True}\n        return self.connection\n\n    async def __aexit__(self, exc_type, exc_val, exc_tb):\n        print(\"Closing connection\")\n        await asyncio.sleep(0.1)  # Simulate cleanup\n        self.connection = None\n\nasync def query_database():\n    \"\"\"Use async context manager.\"\"\"\n    async with AsyncDatabaseConnection(\"postgresql:\u002F\u002Flocalhost\") as conn:\n        print(f\"Using connection: {conn}\")\n        await asyncio.sleep(0.2)  # Simulate query\n        return {\"rows\": 10}\n\nasyncio.run(query_database())\n```\n\n### Pattern 7: Async Iterators and Generators\n\n```python\nimport asyncio\nfrom typing import AsyncIterator\n\nasync def async_range(start: int, end: int, delay: float = 0.1) -> AsyncIterator[int]:\n    \"\"\"Async generator that yields numbers with delay.\"\"\"\n    for i in range(start, end):\n        await asyncio.sleep(delay)\n        yield i\n\nasync def fetch_pages(url: str, max_pages: int) -> AsyncIterator[dict]:\n    \"\"\"Fetch paginated data asynchronously.\"\"\"\n    for page in range(1, max_pages + 1):\n        await asyncio.sleep(0.2)  # Simulate API call\n        yield {\n            \"page\": page,\n            \"url\": f\"{url}?page={page}\",\n            \"data\": [f\"item_{page}_{i}\" for i in range(5)]\n        }\n\nasync def consume_async_iterator():\n    \"\"\"Consume async iterator.\"\"\"\n    async for number in async_range(1, 5):\n        print(f\"Number: {number}\")\n\n    print(\"\\nFetching pages:\")\n    async for page_data in fetch_pages(\"https:\u002F\u002Fapi.example.com\u002Fitems\", 3):\n        print(f\"Page {page_data['page']}: {len(page_data['data'])} items\")\n\nasyncio.run(consume_async_iterator())\n```\n\n### Pattern 8: Producer-Consumer Pattern\n\n```python\nimport asyncio\nfrom asyncio import Queue\nfrom typing import Optional\n\nasync def producer(queue: Queue, producer_id: int, num_items: int):\n    \"\"\"Produce items and put them in queue.\"\"\"\n    for i in range(num_items):\n        item = f\"Item-{producer_id}-{i}\"\n        await queue.put(item)\n        print(f\"Producer {producer_id} produced: {item}\")\n        await asyncio.sleep(0.1)\n    await queue.put(None)  # Signal completion\n\nasync def consumer(queue: Queue, consumer_id: int):\n    \"\"\"Consume items from queue.\"\"\"\n    while True:\n        item = await queue.get()\n        if item is None:\n            queue.task_done()\n            break\n\n        print(f\"Consumer {consumer_id} processing: {item}\")\n        await asyncio.sleep(0.2)  # Simulate work\n        queue.task_done()\n\nasync def producer_consumer_example():\n    \"\"\"Run producer-consumer pattern.\"\"\"\n    queue = Queue(maxsize=10)\n\n    # Create tasks\n    producers = [\n        asyncio.create_task(producer(queue, i, 5))\n        for i in range(2)\n    ]\n\n    consumers = [\n        asyncio.create_task(consumer(queue, i))\n        for i in range(3)\n    ]\n\n    # Wait for producers\n    await asyncio.gather(*producers)\n\n    # Wait for queue to be empty\n    await queue.join()\n\n    # Cancel consumers\n    for c in consumers:\n        c.cancel()\n\nasyncio.run(producer_consumer_example())\n```\n\n### Pattern 9: Semaphore for Rate Limiting\n\n```python\nimport asyncio\nfrom typing import List\n\nasync def api_call(url: str, semaphore: asyncio.Semaphore) -> dict:\n    \"\"\"Make API call with rate limiting.\"\"\"\n    async with semaphore:\n        print(f\"Calling {url}\")\n        await asyncio.sleep(0.5)  # Simulate API call\n        return {\"url\": url, \"status\": 200}\n\nasync def rate_limited_requests(urls: List[str], max_concurrent: int = 5):\n    \"\"\"Make multiple requests with rate limiting.\"\"\"\n    semaphore = asyncio.Semaphore(max_concurrent)\n    tasks = [api_call(url, semaphore) for url in urls]\n    results = await asyncio.gather(*tasks)\n    return results\n\nasync def main():\n    urls = [f\"https:\u002F\u002Fapi.example.com\u002Fitem\u002F{i}\" for i in range(20)]\n    results = await rate_limited_requests(urls, max_concurrent=3)\n    print(f\"Completed {len(results)} requests\")\n\nasyncio.run(main())\n```\n\n### Pattern 10: Async Locks and Synchronization\n\n```python\nimport asyncio\n\nclass AsyncCounter:\n    \"\"\"Thread-safe async counter.\"\"\"\n\n    def __init__(self):\n        self.value = 0\n        self.lock = asyncio.Lock()\n\n    async def increment(self):\n        \"\"\"Safely increment counter.\"\"\"\n        async with self.lock:\n            current = self.value\n            await asyncio.sleep(0.01)  # Simulate work\n            self.value = current + 1\n\n    async def get_value(self) -> int:\n        \"\"\"Get current value.\"\"\"\n        async with self.lock:\n            return self.value\n\nasync def worker(counter: AsyncCounter, worker_id: int):\n    \"\"\"Worker that increments counter.\"\"\"\n    for _ in range(10):\n        await counter.increment()\n        print(f\"Worker {worker_id} incremented\")\n\nasync def test_counter():\n    \"\"\"Test concurrent counter.\"\"\"\n    counter = AsyncCounter()\n\n    workers = [asyncio.create_task(worker(counter, i)) for i in range(5)]\n    await asyncio.gather(*workers)\n\n    final_value = await counter.get_value()\n    print(f\"Final counter value: {final_value}\")\n\nasyncio.run(test_counter())\n```\n\n## Real-World Applications\n\n### Web Scraping with aiohttp\n\n```python\nimport asyncio\nimport aiohttp\nfrom typing import List, Dict\n\nasync def fetch_url(session: aiohttp.ClientSession, url: str) -> Dict:\n    \"\"\"Fetch single URL.\"\"\"\n    try:\n        async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as response:\n            text = await response.text()\n            return {\n                \"url\": url,\n                \"status\": response.status,\n                \"length\": len(text)\n            }\n    except Exception as e:\n        return {\"url\": url, \"error\": str(e)}\n\nasync def scrape_urls(urls: List[str]) -> List[Dict]:\n    \"\"\"Scrape multiple URLs concurrently.\"\"\"\n    async with aiohttp.ClientSession() as session:\n        tasks = [fetch_url(session, url) for url in urls]\n        results = await asyncio.gather(*tasks)\n        return results\n\nasync def main():\n    urls = [\n        \"https:\u002F\u002Fhttpbin.org\u002Fdelay\u002F1\",\n        \"https:\u002F\u002Fhttpbin.org\u002Fdelay\u002F2\",\n        \"https:\u002F\u002Fhttpbin.org\u002Fstatus\u002F404\",\n    ]\n\n    results = await scrape_urls(urls)\n    for result in results:\n        print(result)\n\nasyncio.run(main())\n```\n\n### Async Database Operations\n\n```python\nimport asyncio\nfrom typing import List, Optional\n\n# Simulated async database client\nclass AsyncDB:\n    \"\"\"Simulated async database.\"\"\"\n\n    async def execute(self, query: str) -> List[dict]:\n        \"\"\"Execute query.\"\"\"\n        await asyncio.sleep(0.1)\n        return [{\"id\": 1, \"name\": \"Example\"}]\n\n    async def fetch_one(self, query: str) -> Optional[dict]:\n        \"\"\"Fetch single row.\"\"\"\n        await asyncio.sleep(0.1)\n        return {\"id\": 1, \"name\": \"Example\"}\n\nasync def get_user_data(db: AsyncDB, user_id: int) -> dict:\n    \"\"\"Fetch user and related data concurrently.\"\"\"\n    user_task = db.fetch_one(f\"SELECT * FROM users WHERE id = {user_id}\")\n    orders_task = db.execute(f\"SELECT * FROM orders WHERE user_id = {user_id}\")\n    profile_task = db.fetch_one(f\"SELECT * FROM profiles WHERE user_id = {user_id}\")\n\n    user, orders, profile = await asyncio.gather(user_task, orders_task, profile_task)\n\n    return {\n        \"user\": user,\n        \"orders\": orders,\n        \"profile\": profile\n    }\n\nasync def main():\n    db = AsyncDB()\n    user_data = await get_user_data(db, 1)\n    print(user_data)\n\nasyncio.run(main())\n```\n\n### WebSocket Server\n\n```python\nimport asyncio\nfrom typing import Set\n\n# Simulated WebSocket connection\nclass WebSocket:\n    \"\"\"Simulated WebSocket.\"\"\"\n\n    def __init__(self, client_id: str):\n        self.client_id = client_id\n\n    async def send(self, message: str):\n        \"\"\"Send message.\"\"\"\n        print(f\"Sending to {self.client_id}: {message}\")\n        await asyncio.sleep(0.01)\n\n    async def recv(self) -> str:\n        \"\"\"Receive message.\"\"\"\n        await asyncio.sleep(1)\n        return f\"Message from {self.client_id}\"\n\nclass WebSocketServer:\n    \"\"\"Simple WebSocket server.\"\"\"\n\n    def __init__(self):\n        self.clients: Set[WebSocket] = set()\n\n    async def register(self, websocket: WebSocket):\n        \"\"\"Register new client.\"\"\"\n        self.clients.add(websocket)\n        print(f\"Client {websocket.client_id} connected\")\n\n    async def unregister(self, websocket: WebSocket):\n        \"\"\"Unregister client.\"\"\"\n        self.clients.remove(websocket)\n        print(f\"Client {websocket.client_id} disconnected\")\n\n    async def broadcast(self, message: str):\n        \"\"\"Broadcast message to all clients.\"\"\"\n        if self.clients:\n            tasks = [client.send(message) for client in self.clients]\n            await asyncio.gather(*tasks)\n\n    async def handle_client(self, websocket: WebSocket):\n        \"\"\"Handle individual client connection.\"\"\"\n        await self.register(websocket)\n        try:\n            async for message in self.message_iterator(websocket):\n                await self.broadcast(f\"{websocket.client_id}: {message}\")\n        finally:\n            await self.unregister(websocket)\n\n    async def message_iterator(self, websocket: WebSocket):\n        \"\"\"Iterate over messages from client.\"\"\"\n        for _ in range(3):  # Simulate 3 messages\n            yield await websocket.recv()\n```\n\n## Performance Best Practices\n\n### 1. Use Connection Pools\n\n```python\nimport asyncio\nimport aiohttp\n\nasync def with_connection_pool():\n    \"\"\"Use connection pool for efficiency.\"\"\"\n    connector = aiohttp.TCPConnector(limit=100, limit_per_host=10)\n\n    async with aiohttp.ClientSession(connector=connector) as session:\n        tasks = [session.get(f\"https:\u002F\u002Fapi.example.com\u002Fitem\u002F{i}\") for i in range(50)]\n        responses = await asyncio.gather(*tasks)\n        return responses\n```\n\n### 2. Batch Operations\n\n```python\nasync def batch_process(items: List[str], batch_size: int = 10):\n    \"\"\"Process items in batches.\"\"\"\n    for i in range(0, len(items), batch_size):\n        batch = items[i:i + batch_size]\n        tasks = [process_item(item) for item in batch]\n        await asyncio.gather(*tasks)\n        print(f\"Processed batch {i \u002F\u002F batch_size + 1}\")\n\nasync def process_item(item: str):\n    \"\"\"Process single item.\"\"\"\n    await asyncio.sleep(0.1)\n    return f\"Processed: {item}\"\n```\n\n### 3. Avoid Blocking Operations\n\n```python\nimport asyncio\nimport concurrent.futures\nfrom typing import Any\n\ndef blocking_operation(data: Any) -> Any:\n    \"\"\"CPU-intensive blocking operation.\"\"\"\n    import time\n    time.sleep(1)\n    return data * 2\n\nasync def run_in_executor(data: Any) -> Any:\n    \"\"\"Run blocking operation in thread pool.\"\"\"\n    loop = asyncio.get_event_loop()\n    with concurrent.futures.ThreadPoolExecutor() as pool:\n        result = await loop.run_in_executor(pool, blocking_operation, data)\n        return result\n\nasync def main():\n    results = await asyncio.gather(*[run_in_executor(i) for i in range(5)])\n    print(results)\n\nasyncio.run(main())\n```\n\n## Common Pitfalls\n\n### 1. Forgetting await\n\n```python\n# Wrong - returns coroutine object, doesn't execute\nresult = async_function()\n\n# Correct\nresult = await async_function()\n```\n\n### 2. Blocking the Event Loop\n\n```python\n# Wrong - blocks event loop\nimport time\nasync def bad():\n    time.sleep(1)  # Blocks!\n\n# Correct\nasync def good():\n    await asyncio.sleep(1)  # Non-blocking\n```\n\n### 3. Not Handling Cancellation\n\n```python\nasync def cancelable_task():\n    \"\"\"Task that handles cancellation.\"\"\"\n    try:\n        while True:\n            await asyncio.sleep(1)\n            print(\"Working...\")\n    except asyncio.CancelledError:\n        print(\"Task cancelled, cleaning up...\")\n        # Perform cleanup\n        raise  # Re-raise to propagate cancellation\n```\n\n### 4. Mixing Sync and Async Code\n\n```python\n# Wrong - can't call async from sync directly\ndef sync_function():\n    result = await async_function()  # SyntaxError!\n\n# Correct\ndef sync_function():\n    result = asyncio.run(async_function())\n```\n\n## Testing Async Code\n\n```python\nimport asyncio\nimport pytest\n\n# Using pytest-asyncio\n@pytest.mark.asyncio\nasync def test_async_function():\n    \"\"\"Test async function.\"\"\"\n    result = await fetch_data(\"https:\u002F\u002Fapi.example.com\")\n    assert result is not None\n\n@pytest.mark.asyncio\nasync def test_with_timeout():\n    \"\"\"Test with timeout.\"\"\"\n    with pytest.raises(asyncio.TimeoutError):\n        await asyncio.wait_for(slow_operation(5), timeout=1.0)\n```\n\n## Resources\n\n- **Python asyncio documentation**: https:\u002F\u002Fdocs.python.org\u002F3\u002Flibrary\u002Fasyncio.html\n- **aiohttp**: Async HTTP client\u002Fserver\n- **FastAPI**: Modern async web framework\n- **asyncpg**: Async PostgreSQL driver\n- **motor**: Async MongoDB driver\n\n## Best Practices Summary\n\n1. **Use asyncio.run()** for entry point (Python 3.7+)\n2. **Always await coroutines** to execute them\n3. **Use gather() for concurrent execution** of multiple tasks\n4. **Implement proper error handling** with try\u002Fexcept\n5. **Use timeouts** to prevent hanging operations\n6. **Pool connections** for better performance\n7. **Avoid blocking operations** in async code\n8. **Use semaphores** for rate limiting\n9. **Handle task cancellation** properly\n10. **Test async code** with pytest-asyncio\n",{"name":5,"description":7},"main","7850740bd837adb32f0a109ab2af82482196c6f2","skills\u002F_collections\u002Fplugins\u002Fpython-development\u002Fskills\u002Fasync-python-patterns",1,"https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills","https:\u002F\u002Fzturnsgo.com","https:\u002F\u002Fgithub.com\u002Fshengdabai","https:\u002F\u002Fzturnsgo.com\u002F","AI × education creator — producer, not consumer. Taught 6,000+ learners; shipping learning tools & daily essays with Claude Code, practicing @xiaolai's way 🥋","2026-11-01 21:28:23",{"source":8,"skillName":5,"commands":58,"prompt":68,"zipAvailable":69},[59,62,65],{"tool":60,"command":61},"npx","npx skills add shengdabai\u002FTony-Claude-Code-Skills --skill async-python-patterns",{"tool":63,"command":64},"bunx","bunx skills add shengdabai\u002FTony-Claude-Code-Skills --skill async-python-patterns",{"tool":66,"command":67},"pnpm","pnpm dlx skills add shengdabai\u002FTony-Claude-Code-Skills --skill async-python-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002F_collections\u002Fplugins\u002Fpython-development\u002Fskills\u002Fasync-python-patterns\u002FSKILL.md",true,[],[72,91,121,146,168,188],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":83,"publishedAt":42},"01M70P17DAD4C1C47NPH6A96EM","xiaolai-methodology","以李笑来(Li Xiaolai)的思考方式、方法论与表达风格,为用户做全方位 1-on-1 教练指导,覆盖创业、赚钱、投资、学习、自学、读书写作、用 AI、以及人生心态与自我管理。当用户提到 \"李笑来\"、\"笑来\"、\"笑来老师\"、\"扮演李笑来\"、\"找笑来聊聊\"、\"笑来怎么看\"、\"xiaolai\"、\"把时间当作朋友\"、\"通往财富自由之路\"、\"定投改变命运\"、\"韭菜的自我修养\"、\"自学是门手艺\"、\"让时间陪你慢慢变富\"、\"七年就是一辈子\"、\"元认知\"、\"活在未来\"、\"复利\u002F长期主义\"、\"践行\"、\"痴迷改进\"、\"个人商业模式\u002F出售时间\"、\"睡后收入\"、\"定投\"、\"财富自由\"、\"操作系统升级\"、\"最少必要知识\"、\"北极星提示词\"、\"用 AI 该怎么学\u002F思考\" 等任一触发词,或当用户带着关于创业\u002F赚钱\u002F投资\u002F学习\u002F职业\u002F重大人生决策的困惑、希望被人用笑来式的「逻辑 + 大白话 + 类比 + 重新定义 + 践行导向」来点醒和指导时,自动进入李笑来教练模式。","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fxiaolai-methodology\u002FSKILL.md",[78],{"categoryNo":79,"categoryName":80,"taxonomyType":81,"taxonomyTypeDesc":82},"01JBSEEDCAT000000000000018","写作与文案","SCENARIO","使用场景",[84,85,86,87,88,89,90],"methodology","xiaolai","xiaolai methodology","朋友","投资","writing","收入",{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":101,"publishedAt":42},"01M70P13NB9YP7ACJR1S861CDS","zread","Produce and consume a wiki-style knowledge base for a code repository via the `zread` CLI and its on-disk output under `.\u002F.zread\u002Fwiki\u002F`. Use this skill whenever the user wants to understand, onboard onto, explore, summarize, map, or get an overview of an unfamiliar codebase; asks for architecture docs, a project wiki, a repo walkthrough, module\u002Fpackage explanations, or \"what does this repo do\"; wants to generate, regenerate, resume, browse, or serve code documentation locally; or mentions zread \u002F zread.ai directly. Also use it proactively before diving into a large unknown repo — if `.\u002F.zread\u002Fwiki\u002Fcurrent` exists, read the generated pages instead of crawling source file-by-file; if it doesn't, consider offering to run `zread generate`. The trigger is the intent (understand a codebase through generated docs), not the literal word \"zread\".","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fzread\u002FSKILL.md",[97,100],{"categoryNo":98,"categoryName":99,"taxonomyType":81,"taxonomyTypeDesc":82},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[93,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120],"knowledge","wiki","explore","walkthrough","project","get","knowledge base","run","generate","intent","cli","map","documentation","project wiki","disk","architecture","code","unknown","generated",{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":125,"categories":126,"keywords":131,"publishedAt":42},"01M70P10S4SWMZQ8BJAFBFDRW3","youtube","Launch the YouTube Creator Agent to auto-generate videos.\nUse when: user types \u002Fyoutube, wants to create YouTube videos,\ngenerate video content, or upload to YouTube.\nKeywords: youtube, video, 视频, 创作视频, 发布视频","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fyoutube\u002FSKILL.md",[127,128],{"categoryNo":98,"categoryName":99,"taxonomyType":81,"taxonomyTypeDesc":82},{"categoryNo":129,"categoryName":130,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000036","内容创作者",[123,132,133,134,135,136,137,138,110,139,140,141,39,33,142,143,144,145],"user","content","视频","creator","generate video","videos","launch","video content","create","upload","auto","types","Video","创作",{"skillNo":147,"name":148,"nameZh":6,"description":149,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":150,"categories":151,"keywords":153,"publishedAt":42},"01M70P0YE95D8BACZCGV8BK90K","youtube-script-sync","Sync, update, or optimize Tony's GetNote knowledge base `Youtube视频逐字稿` by turning each parent recording or first-person idea note into an idempotent child note containing a directly recordable YouTube long-video or Shorts script. Use when the user says “更新\u002F同步\u002F优化 Youtube视频逐字稿知识库”, or says “更新\u002F同步\u002F优化该知识库” while this knowledge base is the active context.","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fyoutube-script-sync\u002FSKILL.md",[152],{"categoryNo":98,"categoryName":99,"taxonomyType":81,"taxonomyTypeDesc":82},[154,155,123,156,157,144,158,159,160,161,162,163,164,165,108,166,39,33,102,167],"sync","script","youtube script sync","recording","shorts","first","base","person","update","active","child","optimize","idempotent","long",{"skillNo":169,"name":170,"nameZh":6,"description":171,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":172,"categories":173,"keywords":178,"publishedAt":42},"01M70P0WMV5XT0EEC0N445PW07","writing-skills","How to write SKILL.md files that trigger reliably and teach effectively. Use when creating, improving, or reviewing Claude Code skills.","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fxiaolai\u002Fnlpm\u002Fskills\u002Fnlpm\u002Fwriting-skills\u002FSKILL.md",[174,175,176,177],{"categoryNo":79,"categoryName":80,"taxonomyType":81,"taxonomyTypeDesc":82},{"categoryNo":98,"categoryName":99,"taxonomyType":81,"taxonomyTypeDesc":82},{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":129,"categoryName":130,"taxonomyType":21,"taxonomyTypeDesc":22},[179,89,180,181,182,183,118,39,33,184,185,186,187],"writing skills","how","teach","write skill","write","claude code skills","files","how to","trigger",{"skillNo":189,"name":190,"nameZh":6,"description":191,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":192,"categories":193,"keywords":196,"publishedAt":42},"01M70P0SJFR4YVJQBGMHKGSKXT","writing-rules","How to write .claude\u002Frules\u002F files that Claude actually follows. Use when creating, improving, or reviewing project rules.","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fxiaolai\u002Fnlpm\u002Fskills\u002Fnlpm\u002Fwriting-rules\u002FSKILL.md",[194,195],{"categoryNo":79,"categoryName":80,"taxonomyType":81,"taxonomyTypeDesc":82},{"categoryNo":129,"categoryName":130,"taxonomyType":21,"taxonomyTypeDesc":22},[197,89,198,106,199,185,39,180,183,33,186],"Rules","writing rules","project rules"]