मुख्य सामग्री पर जाएँ
Skillpedia
API और सर्वर (backend)41k · #6755

async-python-patterns

यह क्या करती है

Python से तेज़ और ज़्यादा कुशल programs बनाने में मदद करता है। इससे program एक साथ कई काम कर सकता है और किसी काम के इंतज़ार में रुककर पूरा program जाम नहीं होता, खासकर जब इंटरनेट से data का इंतज़ार करना हो।

कब इस्तेमाल करें

  • ✓ऐसी websites या apps बनाना जिन्हें जल्दी जवाब देना हो।
  • ✓इंटरनेट से बहुत सारी जानकारी एक साथ download करना।
  • ✓किसी चीज़ का इंतज़ार करते हुए बाकी सब कुछ चालू रखना।

Skill का लिंक

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

इसे कॉपी करके अपने AI (Claude, ChatGPT या Cursor) में पेस्ट करें और निर्देशों का पालन करने को कहें।

कैसे इस्तेमाल करें

सबसे आसान तरीका: मैसेज कॉपी करके अपने AI में पेस्ट करें। वह skill पढ़कर निर्देशों का पालन करेगा।

पेस्ट करने के लिए तैयार मैसेज

इस skill से मेरी मदद करो: https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/async-python-patterns/SKILL.md इस लिंक की SKILL.md फ़ाइल पढ़ो और मेरे काम में उसके निर्देशों का पालन करो।
क्या आप चाहते हैं कि आपका AI ऐसी skills खुद ढूँढे?मुफ़्त Skillpedia MCP इंस्टॉल करें: बस एक लाइन, और हर काम से पहले यह 15,000+ skills में खोजता है।1 मिनट में इंस्टॉल करें →

AI से क्या माँगें: उदाहरण

“मैं अपने Python program से एक साथ कई web pages कैसे download कर सकता हूं?”

हर हफ़्ते 5 नई skills, 1 मिनट में पढ़ें।

यह कैसे काम करती है

यह task संभालने के लिए 'event loop' का इस्तेमाल करता है। जब कोई task इंतज़ार कर रहा हो, तो loop दूसरे task पर चला जाता है। `async` और `await` keywords इन रुकने और फिर चालू होने को व्यवस्थित करने में मदद करते हैं।

तकनीकी सामग्री (मूल 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' (synchronous) एक ही लेन वाली सड़क जैसा है: एक बार में एक गाड़ी। 'Async' (asynchronous) कई लेन वाले highway जैसा है: गाड़ियां एक साथ चल सकती हैं, और कुछ थोड़ी देर रुकें भी तो बाकी को नहीं रोकतीं।

'coroutine' क्या है?

यह एक खास Python function है (जिसे `async def` से लिखा जाता है), जिसे रोका और फिर से चालू किया जा सकता है, ताकि इंतज़ार के दौरान program बाकी काम कर सके।

'async' का इस्तेमाल कब नहीं करना चाहिए?

अगर आपका program बहुत ज़्यादा heavy calculation करता है (इंतज़ार वाले network या disk I/O की जगह), तो '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
अपडेट की गई
15/10/2026

क्या यह skill काम की है?

0

लॉग इन करें वोट करने के लिए।

कमेंट

  • …

इस repository की और skills

मिलती-जुलती skills