0Pricing
Python Academy · Lesson

Async Context Managers and Iterators

Implement async with and async for protocols.

async with Statement

Use async with for context managers whose setup/teardown involves awaiting I/O. The managed object must implement __aenter__ and __aexit__.

import asyncio

class AsyncFile:
    async def __aenter__(self):
        print("open")
        return self
    async def __aexit__(self, *args):
        print("close")

async def main():
    async with AsyncFile() as f:
        print("using")

asyncio.run(main())

__aenter__ and __aexit__

Both are coroutines. __aenter__ is awaited on entry; __aexit__ is awaited on exit even if an exception occurred.

import asyncio

class DBSession:
    async def __aenter__(self):
        self.conn = await async_connect()
        return self.conn

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            await self.conn.rollback()
        else:
            await self.conn.commit()
        await self.conn.close()
        return False

All lessons in this course

  1. Coroutines and the event loop
  2. await, Tasks, and Gathering
  3. Async Context Managers and Iterators
  4. Async I/O Patterns in Production
← Back to Python Academy