with — Expert Examples
Wraps a block with a context manager for automatic setup/teardown
Async context managers
Using 'async with' for async resource management.
python
import asyncio class AsyncConnection: def __init__(self, name): self.name = name async def __aenter__(self): print(f"Async connecting to {self.name}") await asyncio.sleep(0) return self async def __aexit__(self, *args): print(f"Async disconnecting from {self.name}") await asyncio.sleep(0) async def main(): async with AsyncConnection("database") as conn: print(f"Using {conn.name}") asyncio.run(main) # Bytecode comparison import dis def sync_ctx(): with open("x"): pass print("\nWith statement bytecode:") dis.dis(sync_ctx)
async with uses __aenter__ and __aexit__ for async setup/teardown. The bytecode uses BEFORE_ASYNC_WITH instead of BEFORE_WITH.
Want to try these examples interactively?
Open Expert Playground