📝 Python

Async Context Managers: async with and @asynccontextmanager

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
112
🌳
Level
Advanced

Async context managers manage resources in async code — connections, files, transactions.

aenter and aexit

class AsyncDB:
    async def __aenter__(self):
        self.conn = await connect("postgresql://localhost/mydb")
        return self.conn

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.conn.close()
        return False  # don't suppress exceptions

async def main():
    async with AsyncDB() as conn:
        result = await conn.fetch("SELECT * FROM users")

@asynccontextmanager — simpler than a class

from contextlib import asynccontextmanager
import httpx

@asynccontextmanager
async def managed_client(base_url: str):
    client = httpx.AsyncClient(base_url=base_url, timeout=30.0)
    try:
        yield client
    finally:
        await client.aclose()

async def main():
    async with managed_client("https://api.example.com") as client:
        r = await client.get("/users")

aiofiles — async file I/O

import aiofiles

async def save_result(filename: str, data: str):
    async with aiofiles.open(filename, "w", encoding="utf-8") as f:
        await f.write(data)

async def read_file(filename: str) -> str:
    async with aiofiles.open(filename, "r", encoding="utf-8") as f:
        return await f.read()

# Line-by-line — don't load everything into memory
async def process_large_file(filename: str):
    async with aiofiles.open(filename) as f:
        async for line in f:
            await process_line(line.strip())

Nested context managers

async def main():
    async with (
        httpx.AsyncClient() as client,
        aiofiles.open("results.json", "w") as f,
    ):
        for url in urls:
            data = await client.get(url)
            await f.write(data.text + "\n")

Python 3.10+ supports parenthesized syntax for multiple async with — no backslashes needed.

Pattern: async context manager for transactions

@asynccontextmanager
async def transaction(conn):
    await conn.execute("BEGIN")
    try:
        yield conn
        await conn.execute("COMMIT")
    except Exception:
        await conn.execute("ROLLBACK")
        raise

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

Event Loop in Python: How asyncio Achieves "Paral…

Event loop is the heart of asyncio. It doesn't run code in parallel across multiple...

📅 30.06.2026 👁️ 125
📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 132
📝

pip: Python Package Manager

Охватываемые темы: Installing packages, Upgrading and removing, requirements.txt, Virtual environment.

📅 30.06.2026 👁️ 120

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!