python-async-patterns について
asyncio で並行プログラムを作る Python 開発者向けのリファレンススキルです。タスク管理、同時実行数の制限、タイムアウト、非同期コンテキストマネージャー、よくある問題を解説し、スクリプトとテンプレートも含みます。
主な機能
- 01gather と TaskGroup による並行タスク
- 02Semaphore による同時実行数の制限
- 03タイムアウトと非同期コンテキストマネージャー
- 04ブロッキング呼び出しや孤立タスクへの注意
- 05リファレンス、スクリプト、プロジェクトテンプレート
活用シーン
- 01複数項目の並行取得や処理
- 02リソース保護のための同時実行数制限
- 03時間のかかる処理へのタイムアウト設定
- 04非同期コード内のブロッキング呼び出しの確認
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ 0xdarkmatter/ claude-mods --skill python-async-patternsインストール後、Claude Code で/python-async-patternsを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
assets/async-project-template.pyreferences/aiohttp-patterns.mdconcurrency-patterns.mddebugging-async.mderror-handling.mdmixing-sync-async.mdperformance.mdproduction-patterns.mdscripts/find-blocking-calls.sh詳細
Python の非同期パターン
並行 Python プログラミングのための asyncio パターンです。
基本概念
import asyncio
# Coroutine (must be awaited)
async def fetch(url: str) -> str:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
# Entry point
async def main():
result = await fetch("https://example.com")
return result
asyncio.run(main())
パターン 1:gather による並行処理
async def fetch_all(urls: list[str]) -> list[str]:
"""Fetch multiple URLs concurrently."""
async with aiohttp.ClientSession() as session:
tasks = [fetch_one(session, url) for url in urls]
return await asyncio.gather(*tasks, return_exceptions=True)
パターン 2:並行処理数の制限
async def fetch_with_limit(urls: list[str], limit: int = 10):
"""Limit concurrent requests."""
semaphore = asyncio.Semaphore(limit)
async def bounded_fetch(url):
async with semaphore:
return await fetch_one(url)
return await asyncio.gather(*[bounded_fetch(url) for url in urls])
パターン 3:TaskGroup(Python 3.11 以降)
async def process_items(items):
"""Structured concurrency with automatic cleanup."""
async with asyncio.TaskGroup() as tg:
for item in items:
tg.create_task(process_one(item))
# All tasks complete here, or exception raised
パターン 4:タイムアウト
async def with_timeout():
try:
async with asyncio.timeout(5.0): # Python 3.11+
result = await slow_operation()
except asyncio.TimeoutError:
result = None
return result
重要な警告
# WRONG - blocks event loop
async def bad():
time.sleep(5) # Never use time.sleep!
requests.get(url) # Blocking I/O!
# CORRECT
async def good():
await asyncio.sleep(5)
async with aiohttp.ClientSession() as s:
await s.get(url)
# WRONG - orphaned task
async def bad():
asyncio.create_task(work()) # May be garbage collected!
# CORRECT - keep reference
async def good():
task = asyncio.create_task(work())
await task
クイックリファレンス
| パターン | 用途 |
|---|---|
gather(*tasks) | 複数の独立した処理 |
Semaphore(n) | レート制限、リソース制約 |
TaskGroup() | 構造化並行処理(3.11 以降) |
Queue() | プロデューサー・コンシューマー |
timeout(s) | タイムアウトラッパー(3.11 以降) |
Lock() | 共有された可変状態 |
非同期コンテキストマネージャー
from contextlib import asynccontextmanager
@asynccontextmanager
async def managed_connection():
conn = await create_connection()
try:
yield conn
finally:
await conn.close()
追加リソース
詳細なパターンについては、以下を読み込んでください。
./references/concurrency-patterns.md- Queue、Lock、プロデューサー・コンシューマー./references/aiohttp-patterns.md- HTTP クライアント/サーバーのパターン./references/mixing-sync-async.md- run_in_executor、スレッドプール./references/debugging-async.md- デバッグモード、プロファイリング、問題の特定./references/production-patterns.md- グレースフルシャットダウン、ヘルスチェック、シグナル処理./references/error-handling.md- バックオフ付きリトライ、サーキットブレーカー、部分的な障害./references/performance.md- uvloop、コネクションプーリング、バッファーサイズの設定
スクリプト
./scripts/find-blocking-calls.sh- 非同期関数内のブロッキング呼び出しをコードから検出します
アセット
./assets/async-project-template.py- 本番環境対応の非同期アプリのひな形
関連項目
前提条件:
python-typing-patterns- 非同期関数の型ヒント
関連スキル:
python-fastapi-patterns- 非同期 Web APIpython-observability-patterns- 非同期ログ記録とトレーシングpython-database-patterns- 非同期データベースアクセス
コメント
Markdown 対応