async-python-patterns
Fungsinya
Membantu membuat program Python yang lebih cepat dan efisien. Program bisa mengerjakan beberapa hal sekaligus tanpa macet, terutama saat harus menunggu sesuatu (misalnya data dari internet).
Kapan dipakai
- ✓Membangun website atau aplikasi yang harus merespons dengan cepat.
- ✓Mengunduh banyak informasi dari internet sekaligus.
- ✓Membuat program menunggu sesuatu tanpa menghentikan semua pekerjaan lain.
Link skill
https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/async-python-patterns/SKILL.mdSalin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.
Cara pakai
Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.
Pesan siap tempel
Untuk Claude Code, Codex, atau Cursor: jalankan di folder proyek, lalu skill langsung terpasang.
Unduh SKILL.md lalu taruh di folder skill agen Anda.
Contoh permintaan ke AI
“Bagaimana cara membuat program Python saya mengunduh beberapa halaman web secara bersamaan?”
5 skill baru setiap minggu. 1 menit baca.
Cara kerjanya
Program menggunakan 'event loop' untuk mengatur tugas-tugas. Ketika satu tugas harus menunggu, event loop beralih ke tugas lain. Kata kunci `async` dan `await` membantu mengatur jeda dan lanjutan proses ini.
Konten teknis (SKILL.md asli)
Teks asli dari pembuat, dalam bahasa Inggris, langsung dari 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)
…
Pertanyaan umum
Apa perbedaan antara 'sync' dan 'async'?
'Sync' (synchronous) seperti jalan satu lajur: satu kendaraan dalam satu waktu. 'Async' (asynchronous) seperti jalan tol bertingkat: kendaraan bisa berjalan bersamaan, dan sebagian mungkin menunggu sebentar tanpa menghalangi yang lain.
Apa itu 'coroutine'?
Ini adalah fungsi khusus di Python (ditandai dengan `async def`) yang bisa dijeda dan dilanjutkan kembali, sehingga program bisa mengerjakan hal lain selama menunggu.
Kapan sebaiknya TIDAK menggunakan 'async'?
Jika program banyak melakukan perhitungan berat (bukan menunggu jaringan atau disk), menggunakan 'async' mungkin tidak membantu dan bahkan bisa membuat kode lebih rumit. Teknik lain biasanya lebih cocok untuk kasus seperti itu.
Detail
Deskripsi asli dari pembuat
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
Popularitas
- Bintang GitHub
- 41k
- Peringkat
- #6755
- Lisensi
- MIT
- Diperbarui
- 15/10/2026
Komentar
- …
Skill lain dari repositori ini
screen-reader-testing
41kMeminta agent Anda menguji website menggunakan screen reader untuk memastikan website dapat diakses.
wcag-audit-patterns
41kMembantu agent Anda mengaudit aksesibilitas website dan memperbaiki masalah sesuai panduan WCAG.
multi-reviewer-patterns
41kMemungkinkan agent Anda mengoordinasikan code review paralel, menghapus temuan ganda, dan menggabungkan laporan.
parallel-debugging
41kMemungkinkan agent Anda men-debug masalah rumit dengan investigasi paralel dan analisis akar masalah.
Skill serupa
api-connector-builder
280kMembuat agent Anda membangun koneksi API baru mengikuti pola yang sudah ada. Gunakan saat ingin menambah integrasi lagi tanpa membuat cara baru.
api-design
280kMembantu agent Anda merancang REST API sesuai praktik terbaik. Berguna untuk mengatur cara API berkomunikasi, menampilkan error, dan mengorganisasi data.
backend-patterns
280kMembantu agent Anda dengan pola arsitektur sisi server dan optimasi database. Berguna untuk membangun atau meninjau kode yang berjalan di server.