Python AsyncIO Cheat Sheet
Covers async/await syntax, creating and gathering concurrent tasks, synchronization primitives, and timeout/error handling patterns.
2 PagesAdvancedMar 25, 2026
Coroutines & await
Define and run coroutine functions.
python
import asyncioasync def fetch_data(delay): await asyncio.sleep(delay) # Non-blocking sleep return f"data after {delay}s"async def main(): result = await fetch_data(1) print(result)asyncio.run(main()) # Entry point: creates and runs the event loop
Tasks & Concurrent Execution
Run multiple coroutines concurrently.
python
import asyncioasync def main(): # Schedule coroutines to run concurrently task1 = asyncio.create_task(fetch_data(1)) task2 = asyncio.create_task(fetch_data(2)) result1 = await task1 result2 = await task2 # Or gather many at once, preserving input order in the results results = await asyncio.gather( fetch_data(1), fetch_data(2), fetch_data(3) ) # Wait for just the first to finish done, pending = await asyncio.wait( [task1, task2], return_when=asyncio.FIRST_COMPLETED )asyncio.run(main())
Synchronization Primitives
Coordinate access between coroutines.
python
import asynciolock = asyncio.Lock()sem = asyncio.Semaphore(3) # Limit to 3 concurrent tasksasync def worker(n): async with sem: # Acquire/release semaphore async with lock: # Acquire/release mutex print(f"worker {n} running") await asyncio.sleep(1)queue = asyncio.Queue()async def producer(): for i in range(5): await queue.put(i)async def consumer(): while True: item = await queue.get() print(f"consumed {item}") queue.task_done()
Timeouts & Error Handling
Guard against slow or failing coroutines.
python
import asyncioasync def main(): try: result = await asyncio.wait_for(fetch_data(5), timeout=2) except asyncio.TimeoutError: print("Timed out!") # gather() with exceptions captured instead of raised results = await asyncio.gather( fetch_data(1), bad_coro(), return_exceptions=True ) for r in results: if isinstance(r, Exception): print("failed:", r)
Key Concepts
Core vocabulary for asyncio code.
- async def- Defines a coroutine function; calling it returns a coroutine object, not the result
- await- Suspends the coroutine until the awaited object completes, yielding control to the event loop
- asyncio.create_task()- Schedules a coroutine to run concurrently on the event loop, returns immediately
- asyncio.run()- Creates a new event loop, runs the coroutine to completion, and closes the loop
- Event loop- The single-threaded scheduler that runs coroutines/tasks and dispatches I/O callbacks
- async with / async for- Async context managers and iterators for use inside coroutines
Pro Tip
asyncio gives concurrency, not parallelism — it's built for I/O-bound work like network and disk calls. CPU-bound code still blocks the single-threaded event loop; offload it with loop.run_in_executor() or a ProcessPoolExecutor.
Was this cheat sheet helpful?
Explore Topics
#PythonAsyncIO#PythonAsyncIOCheatSheet#Programming#Advanced#CoroutinesAwait#TasksConcurrentExecution#SynchronizationPrimitives#TimeoutsErrorHandling#Concurrency#ErrorHandling#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance