Python Async/Await Cheatsheet
Quick reference for Python async/await: async functions, await expressions, asyncio module, tasks, event loops, and concurrency patterns.
| Feature | Description | Example | Category |
|---|---|---|---|
| async def | Define an asynchronous function | async def fetch_data(): return 42 | Basics |
| await | Wait for a coroutine result | result = await fetch_data() | Basics |
| asyncio.run() | Run the main coroutine | import asyncio asyncio.run(main()) | asyncio |
| asyncio.sleep() | Non-blocking sleep | await asyncio.sleep(1) | asyncio |
| asyncio.get_event_loop() | Get current event loop | loop = asyncio.get_event_loop() | asyncio |
| asyncio.create_task() | Schedule a coroutine concurrently | task = asyncio.create_task(fetch_data()) | Tasks & Futures |
| asyncio.gather() | Run multiple coroutines concurrently | results = await asyncio.gather(task1, task2) | Tasks & Futures |
| asyncio.wait() | Wait for multiple coroutines | done, pending = await asyncio.wait([task1, task2]) | Tasks & Futures |
| Semaphore | Limit concurrent access | sem = asyncio.Semaphore(3) async with sem: await task() | Concurrency Patterns |
| Queue | Async queue for producer/consumer | queue = asyncio.Queue() await queue.put(data) data = await queue.get() | Concurrency Patterns |
| async for | Iterate over asynchronous iterator | async for item in aiterable: print(item) | Advanced |
| async with | Async context manager | async with aiofile.open("file.txt", "r") as f: contents = await f.read() | Advanced |
| Exception Handling | Try/except in async functions | try: await fetch_data() except Exception as e: print(e) | Advanced |