jpskill.com
🛠️ 開発・MCP コミュニティ

python-async-patterns

Pythonのasyncioを用いた非同期プログラミングにおいて、並行処理のパターンを効率的に実装するためのSkillです。

📜 元の英語説明(参考)

Python asyncio patterns for concurrent programming. Triggers on: asyncio, async, await, coroutine, gather, semaphore, TaskGroup, event loop, aiohttp, concurrent.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Pythonのasyncioを用いた非同期プログラミングにおいて、並行処理のパターンを効率的に実装するためのSkillです。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o python-async-patterns.zip https://jpskill.com/download/5920.zip && unzip -o python-async-patterns.zip && rm python-async-patterns.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/5920.zip -OutFile "$d\python-async-patterns.zip"; Expand-Archive "$d\python-async-patterns.zip" -DestinationPath $d -Force; ri "$d\python-async-patterns.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して python-async-patterns.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → python-async-patterns フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-17
取得日時
2026-05-17
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Python Async パターン

並行PythonプログラミングのためのAsyncioパターンです。

コアコンセプト

import asyncio

# コルーチン (awaitされる必要があります)
async def fetch(url: str) -> str:
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

# エントリーポイント
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]:
    """複数のURLを並行してフェッチします。"""
    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):
    """並行リクエストを制限します。"""
    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):
    """自動クリーンアップによる構造化された並行処理。"""
    async with asyncio.TaskGroup() as tg:
        for item in items:
            tg.create_task(process_one(item))
    # すべてのタスクがここで完了するか、例外が送出されます

パターン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

重要な警告

# 誤り - イベントループをブロックします
async def bad():
    time.sleep(5)         # time.sleepは絶対に使用しないでください!
    requests.get(url)     # ブロッキングI/O!

# 正しい
async def good():
    await asyncio.sleep(5)
    async with aiohttp.ClientSession() as s:
        await s.get(url)
# 誤り - 孤立したタスク
async def bad():
    asyncio.create_task(work())  # ガベージコレクションされる可能性があります!

# 正しい - 参照を保持します
async def good():
    task = asyncio.create_task(work())
    await task

クイックリファレンス

パターン ユースケース
gather(*tasks) 複数の独立した操作
Semaphore(n) レート制限、リソース制約
TaskGroup() 構造化された並行処理 (3.11+)
Queue() プロデューサー・コンシューマー
timeout(s) タイムアウトラッパー (3.11+)
Lock() 共有可能なミュータブルな状態

Asyncコンテキストマネージャー

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 - async関数内のブロッキング呼び出しをコードスキャンします

アセット

  • ./assets/async-project-template.py - 本番環境対応のasyncアプリケーションのスケルトン

関連項目

前提条件:

  • python-typing-patterns - async関数の型ヒント

関連スキル:

  • python-fastapi-patterns - Async Web API
  • python-observability-patterns - Asyncロギングとトレース
  • python-database-patterns - Asyncデータベースアクセス
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Python Async Patterns

Asyncio patterns for concurrent Python programming.

Core Concepts

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())

Pattern 1: Concurrent with 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)

Pattern 2: Bounded Concurrency

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])

Pattern 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

Pattern 4: Timeout

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

Critical Warnings

# 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

Quick Reference

Pattern Use Case
gather(*tasks) Multiple independent operations
Semaphore(n) Rate limiting, resource constraints
TaskGroup() Structured concurrency (3.11+)
Queue() Producer-consumer
timeout(s) Timeout wrapper (3.11+)
Lock() Shared mutable state

Async Context Manager

from contextlib import asynccontextmanager

@asynccontextmanager
async def managed_connection():
    conn = await create_connection()
    try:
        yield conn
    finally:
        await conn.close()

Additional Resources

For detailed patterns, load:

  • ./references/concurrency-patterns.md - Queue, Lock, producer-consumer
  • ./references/aiohttp-patterns.md - HTTP client/server patterns
  • ./references/mixing-sync-async.md - run_in_executor, thread pools
  • ./references/debugging-async.md - Debug mode, profiling, finding issues
  • ./references/production-patterns.md - Graceful shutdown, health checks, signal handling
  • ./references/error-handling.md - Retry with backoff, circuit breakers, partial failures
  • ./references/performance.md - uvloop, connection pooling, buffer sizing

Scripts

  • ./scripts/find-blocking-calls.sh - Scan code for blocking calls in async functions

Assets

  • ./assets/async-project-template.py - Production-ready async app skeleton

See Also

Prerequisites:

  • python-typing-patterns - Type hints for async functions

Related Skills:

  • python-fastapi-patterns - Async web APIs
  • python-observability-patterns - Async logging and tracing
  • python-database-patterns - Async database access