async — Advanced Examples
Declares an asynchronous coroutine function or context manager
Async context managers and patterns
Using async with for resource management.
python
import asyncio class AsyncTimer: def __init__(self, label): self.label = label async def __aenter__(self): print(f" [{self.label}] Starting") self.start = asyncio.get_event_loop().time() return self async def __aexit__(self, *args): elapsed = asyncio.get_event_loop().time() - self.start print(f" [{self.label}] Done ({elapsed:.4f}s)") async def main(): async with AsyncTimer("task"): await asyncio.sleep(0.01) # Semaphore for concurrency limiting sem = asyncio.Semaphore(2) async def limited_task(n): async with sem: print(f" Task {n} running") await asyncio.sleep(0.01) await asyncio.gather(*[limited_task(i) for i in range(5)]) asyncio.run(main())
async with calls __aenter__ and __aexit__ which can themselves await. Semaphores limit how many coroutines run a section concurrently.
Want to try these examples interactively?
Open Advanced Playground