contextmanager-async Async with
Last updated: 2026-09-22
contextmanager-async Async with
async with uses an async context manager; __aenter__/__aexit__ are awaited.
| Category | Keywords & Statements |
|---|---|
| Kind | Keyword / Statement |
| Python Version | 3.5+ |
📝 Syntax
async with expr [as var]:
block
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
Ctx
🏷️ Related Keywords / Statements
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhat is the difference between `async with` and a normal `with`?
A`async with` is for asynchronous context managers: entering and exiting `await` the async methods `__aenter__` / `__aexit__`. A normal `with` calls the synchronous `__enter__` / `__exit__`.
QCan `async with` be written inside a normal function?
ANo. `async with` can only appear inside an `async def` function. Writing it in a normal function gives `SyntaxError: 'async with' outside async function`.
QHow can my own class support `async with`?
AImplement two async methods: `async def __aenter__(self)` returning the entered object, and `async def __aexit__(self, exc_type, exc, tb)` doing cleanup. Returning `True` from `__aexit__` swallows the exception; returning `False` (or nothing) lets it propagate.