Python Async/Await Cheatsheet

Quick reference for Python async/await: async functions, await expressions, asyncio module, tasks, event loops, and concurrency patterns.

FeatureDescriptionExampleCategory
async defDefine an asynchronous functionasync def fetch_data(): return 42Basics
awaitWait for a coroutine resultresult = await fetch_data()Basics
asyncio.run()Run the main coroutineimport asyncio asyncio.run(main())asyncio
asyncio.sleep()Non-blocking sleepawait asyncio.sleep(1)asyncio
asyncio.get_event_loop()Get current event looploop = asyncio.get_event_loop()asyncio
asyncio.create_task()Schedule a coroutine concurrentlytask = asyncio.create_task(fetch_data())Tasks & Futures
asyncio.gather()Run multiple coroutines concurrentlyresults = await asyncio.gather(task1, task2)Tasks & Futures
asyncio.wait()Wait for multiple coroutinesdone, pending = await asyncio.wait([task1, task2])Tasks & Futures
SemaphoreLimit concurrent accesssem = asyncio.Semaphore(3) async with sem: await task()Concurrency Patterns
QueueAsync queue for producer/consumerqueue = asyncio.Queue() await queue.put(data) data = await queue.get()Concurrency Patterns
async forIterate over asynchronous iteratorasync for item in aiterable: print(item)Advanced
async withAsync context managerasync with aiofile.open("file.txt", "r") as f: contents = await f.read()Advanced
Exception HandlingTry/except in async functionstry: await fetch_data() except Exception as e: print(e)Advanced