Clean Up with Async Context Managers
Core idea
An async context manager implements awaitable aenter and aexit, allowing acquisition and cleanup to suspend. async with awaits entry and, if entry succeeds, awaits exit even when the body raises. contextlib.asynccontextmanager builds the protocol from an async generator with one yield. Use try/finally around the yield and avoid swallowing failures.
import asyncio
async def main(): from contextlib import asynccontextmanager @asynccontextmanager async def lease(): print('acquire') try: yield 'token' finally: print('release') try: async with lease() as token: print(token) raise ValueError('bad') except ValueError: print('caught')
asyncio.run(main())The exit path runs before the outer handler.
Expected output:
acquiretokenreleasecaughtRelease when a task is cancelled
import asyncio
async def main(): from contextlib import asynccontextmanager @asynccontextmanager async def lease(): try: yield finally: print('release') ready=asyncio.Event() async def work(): async with lease(): ready.set() await asyncio.Event().wait() t=asyncio.create_task(work()) await ready.wait() t.cancel() try: await t except asyncio.CancelledError: print('cancelled')
asyncio.run(main())The event confirms successful entry before cancellation.
Expected output:
releasecancelledCommon mistake
If aenter fails, aexit is not called for that manager; entry must clean up partial acquisitions. Repeated cancellation may interrupt an awaited exit, so complex resources need a deliberate shutdown policy.
Practice
Implement a class-based async context manager returning a label. Test normal exit and a ValueError without suppressing the error.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Async context managers
Check your understanding of async context managers.
What is printed?
import asyncio
async def main(): class C: async def __aenter__(self): return 3 async def __aexit__(self,*args): print('exit') async with C() as x: print(x)
asyncio.run(main())What is printed?
import asyncio
async def main(): from contextlib import asynccontextmanager @asynccontextmanager async def c(): yield 8 async with c() as x: print(x)
asyncio.run(main())What if entry fails before returning?
What should surround yield for cleanup?