Python

Async Context Manager (aiohttp pattern)

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Define an async resource using `@asynccontextmanager` from contextlib. Cleaner than writing a class with __aenter__/__aexit__ for one-off wrappers.
Python
Raw
import asyncio
from contextlib import asynccontextmanager
import aiohttp

@asynccontextmanager
async def http_session(timeout: int = 10):
    session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout))
    try:
        yield session
    finally:
        await session.close()

async def main():
    async with http_session(timeout=5) as session:
        async with session.get("https://api.github.com") as r:
            print(r.status)
    # session is guaranteed-closed here, even on exception

asyncio.run(main())
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.