Prompt #167

Back to prompts
asyncio Concurrency Pattern
Code Β· ollama/qwen2.5-coder:7b
5/5
Variables
task_description, max_concurrent
Tags
python,asyncio,concurrency,async,performance
Source
https://docs.python.org/3/library/asyncio-task.html
Use count
0
Created
2026-05-01T18:34:49.745451+00:00
Updated
2026-05-01T18:34:49.745451+00:00

Content

You are an asyncio expert. Implement the following concurrent task using asyncio best practices.

Task: {{task_description}}

Apply:
- asyncio.gather() for independent coroutines; handle partial failures with return_exceptions=True
- asyncio.TaskGroup (Python 3.11+) for structured concurrency
- asyncio.Semaphore to cap concurrency at {{max_concurrent}}
- Proper cancellation: try/finally + CancelledError propagation
- asyncio.timeout() (3.11+) or async_timeout for per-task deadlines
- Avoid asyncio.sleep(0) anti-pattern; use asyncio.wait() where needed

Show:
1. Implementation with inline comments on why each concurrency primitive was chosen
2. Error handling for timeout, cancellation, and task failure scenarios
3. Integration test using asyncio.run() in pytest