본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)41k · #6755

async-python-patterns

하는 일

Python으로 더 빠르고 효율적인 프로그램을 만드는 방법을 설명합니다. 프로그램이 여러 일을 동시에 하면서도 멈추지 않도록 합니다. 특히 인터넷에서 데이터를 기다려야 할 때 도움이 됩니다.

사용하는 경우

  • ✓빠르게 응답해야 하는 웹사이트나 앱을 만들 때.
  • ✓인터넷에서 많은 정보를 한꺼번에 내려받을 때.
  • ✓한 작업이 기다리는 동안 다른 모든 것을 멈추지 않게 할 때.

스킬 링크

https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/async-python-patterns/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/async-python-patterns/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“Python 프로그램이 여러 웹 페이지를 동시에 내려받게 하려면 어떻게 해야 하나요?”

매주 새 스킬 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.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬