Language Syntax

Async with — Python syntax

Await entry and exit hooks of an asynchronous context manager. Use inside async functions; cleanup occurs when the suite leaves after entry succeeds, and a truthy exit result can suppress an exception. The as target is optional.

Formal Syntax & Structure

python syntaxpython
async with context_expression as target:    suite

Working Example

Example Snippetpython
import asynciofrom contextlib import asynccontextmanager@asynccontextmanagerasync def resource():    yield 7async def run():    async with resource() as n:        return nprint(asyncio.run(run()))
Python Reference