async-python-patterns
できること
Pythonを使って、より速く効率的なプログラムを作るのに役立ちます。プログラムが止まることなく、複数の作業を同時に進められるようにします。特に、インターネット上のデータなど、何かを待つ必要があるときに効果的です。
使う場面
- ✓素早く応答する必要のあるWebサイトやアプリを作るとき。
- ✓インターネットから大量の情報を同時にダウンロードするとき。
- ✓何かを待っている間も、ほかの処理を止めないようにしたいとき。
スキルのリンク
https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/async-python-patterns/SKILL.mdコピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。
使い方
いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。
貼り付け用メッセージ
Claude Code、Codex、Cursorの場合:プロジェクトのフォルダで実行するとスキルがインストールされます。
SKILL.mdをダウンロードして、エージェントのスキル用フォルダに入れてください。
AIへの頼み方の例
“Pythonプログラムで、複数のWebページを同時にダウンロードするにはどうすればよいですか?”
毎週5つの新しいスキル。1分で読めます。
仕組み
「イベントループ」を使ってタスクを管理します。あるタスクが待機状態になると、ループが別のタスクに切り替えます。`async`と`await`という特別なキーワードを使うと、こうした一時停止と再開を整理して書けます。
技術的な内容(元のSKILL.md)
作者による元のテキスト(英語)をGitHubからそのまま表示しています。
Async Python Patterns
Comprehensive guidance for implementing asynchronous Python applications using asyncio, concurrent programming patterns, and async/await for building high-performance, non-blocking systems.
When to Use This Skill
- Building async web APIs (FastAPI, aiohttp, Sanic)
- Implementing concurrent I/O operations (database, file, network)
- Creating web scrapers with concurrent requests
- Developing real-time applications (WebSocket servers, chat systems)
- Processing multiple independent tasks simultaneously
- Building microservices with async communication
- Optimizing I/O-bound workloads
- Implementing async background tasks and queues
Sync vs Async Decision Guide
Before adopting async, consider whether it's the right choice for your use case.
| Use Case | Recommended Approach |
|---|---|
| Many concurrent network/DB calls | asyncio |
| CPU-bound computation | multiprocessing or thread pool |
| Mixed I/O + CPU | Offload CPU work with asyncio.to_thread() |
| Simple scripts, few connections | Sync (simpler, easier to debug) |
| Web APIs with high concurrency | Async frameworks (FastAPI, aiohttp) |
Key Rule: Stay fully sync or fully async within a call path. Mixing creates hidden blocking and complexity.
Core Concepts
1. Event Loop
The event loop is the heart of asyncio, managing and scheduling asynchronous tasks.
Key characteristics:
- Single-threaded cooperative multitasking
- Schedules coroutines for execution
- Handles I/O operations without blocking
- Manages callbacks and futures
2. Coroutines
Functions defined with async def that can be paused and resumed.
Syntax:
async def my_coroutine():
result = await some_async_operation()
return result
3. Tasks
Scheduled coroutines that run concurrently on the event loop.
4. Futures
Low-level objects representing eventual results of async operations.
5. Async Context Managers
Resources that support async with for proper cleanup.
6. Async Iterators
Objects that support async for for iterating over async data sources.
Quick Start
import asyncio
async def main():
print("Hello")
await asyncio.sleep(1)
print("World")
# Python 3.7+
asyncio.run(main())
Fundamental Patterns
Pattern 1: Basic Async/Await
import asyncio
async def fetch_data(url: str) -> dict:
"""Fetch data from URL asynchronously."""
await asyncio.sleep(1) # Simulate I/O
return {"url": url, "data": "result"}
async def main():
result = await fetch_data("https://api.example.com")
print(result)
asyncio.run(main())
Pattern 2: Concurrent Execution with gather()
import asyncio
from typing import List
async def fetch_user(user_id: int) -> dict:
"""Fetch user data."""
await asyncio.sleep(0.5)
return {"id": user_id, "name": f"User {user_id}"}
async def fetch_all_users(user_ids: List[int]) -> List[dict]:
"""Fetch multiple users concurrently."""
tasks = [fetch_user(uid) for uid in user_ids]
results = await asyncio.gather(*tasks)
return results
async def main():
user_ids = [1, 2, 3, 4, 5]
users = await fetch_all_users(user_ids)
print(f"Fetched {len(users)} users")
asyncio.run(main())
Pattern 3: Task Creation and Management
import asyncio
async def background_task(name: str, delay: int):
"""Long-running background task."""
print(f"{name} started")
await asyncio.sleep(delay)
print(f"{name} completed")
return f"Result from {name}"
async def main():
# Create tasks
task1 = asyncio.create_task(background_task("Task 1", 2))
task2 = asyncio.create_task(background_task("Task 2", 1))
# Do other work
print("Main: doing other work")
await asyncio.sleep(0.5)
# Wait for tasks
result1 = await task1
result2 = await task2
print(f"Results: {result1}, {result2}")
asyncio.run(main())
Pattern 4: Error Handling in Async Code
import asyncio
from typing import List, Optional
async def risky_operation(item_id: int) -> dict:
"""Operation that might fail."""
await asyncio.sleep(0.1)
if item_id % 3 == 0:
raise ValueError(f"Item {item_id} failed")
return {"id": item_id, "status": "success"}
async def safe_operation(item_id: int) -> Optional[dict]:
"""Wrapper with error handling."""
try:
return await risky_operation(item_id)
…
よくある質問
「sync」と「async」の違いは何ですか?
「sync」(同期)は一車線の道路のようなもので、一度に一台の車しか進めません。「async」(非同期)は複数車線の高速道路のようなもので、車が同時に進み、一部が少し待っても他の車を止めません。
「コルーチン」とは何ですか?
`async def`で定義される特別なPython関数のことで、一時停止と再開ができます。待っている間に、プログラムが他の処理を行えるようにします。
「async」を使うべきでないのはどんなときですか?
プログラムがネットワークやディスクへの入出力を待つのではなく、重い計算を多く行う場合は、「async」を使っても効果がないどころか、かえって複雑になることがあります。そのような場合は、別の方法の方が適していることがあります。
詳細
作者による元の説明
Master Python asyncio, concurrent programming, and async/await patterns for high-performance applications. Use when building async APIs, concurrent systems, or I/O-bound applications requiring non-blocking operations.
repo: wshobson/agents
人気
- GitHubのスター
- 41k
- ランキング
- #6755
- ライセンス
- MIT
- 更新日
- 2026/10/15
コメント
- …
このリポジトリの他のスキル
screen-reader-testing
41kエージェントにスクリーンリーダーを使ってWebサイトをテストさせ、アクセシビリティを確認します。
wcag-audit-patterns
41kエージェントがWebサイトのアクセシビリティを監査し、WCAGガイドラインに沿って問題を修正できるようにします。
multi-reviewer-patterns
41kエージェントが複数のコードレビューを並行して調整できるようにします。指摘事項の重複を排除し、レポートにまとめます。
parallel-debugging
41kエージェントが並行調査と根本原因分析を使って、複雑な問題をデバッグできるようにします。
似ているスキル
api-connector-builder
280kエージェントが既存のパターンに従って、新しいAPI連携を構築します。新しい方式を作らずに、もう一つ連携を追加したいときに使います。
api-design
280kエージェントがベストプラクティスに沿ってREST APIを設計できるようにします。APIの通信方法、エラーの表示方法、データの整理方法を決めるのに役立ちます。
backend-patterns
280kエージェントのサーバーサイドのアーキテクチャパターンとデータベースの最適化を支援します。サーバー上で動くコードを作成またはレビューするときに役立ちます。