Back
+20 XP
Concept

Async Context Managers (__aenter__ & __aexit__)

Asynchronous resource teardown cannot use standard `with` blocks because network handshakes and buffer flushes are coroutines. Implementing `async def __aenter__` and `async def __aexit__` enables foolproof RAII resource safety using `async with` 🛡️🚪.

python
import asyncio

class AsyncConnection:
    async def __aenter__(self):
        await asyncio.sleep(0.01)
        print("Connection established 🔗")
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await asyncio.sleep(0.01)
        print("Connection closed cleanly 🚪")
        return False # Propagate exceptions

async def main():
    async with AsyncConnection() as conn:
        print("Transmitting queries... 🚀")

asyncio.run(main())

# 27. Async Context Managers (__aenter__ & __aexit__) If releasing a database connection requires executing `await conn.execute("DISCONNECT")` or flushing a network buffer over TLS, a synchronous `__exit__` method will raise `RuntimeError: cannot await in synchronous context` 🛑. ```python import asyncio class MicroLock: def __init__(self): self._lock = asyncio.Lock() async def __aenter__(self): await self._lock.acquire() return self async def __aexit__(self, exc_type, exc_val, exc_tb): self._lock.release() ``` ### The Async Context Contract 1. **`__aenter__()`**: An async method called before entering the block. Its return value is bound to the target in `async with ... as target:`. 2. **`__aexit__()`**: An async method executed upon block exit. It receives `(exc_type, exc_val, exc_tb)`. 3. **Exception Suppression**: Returning `True` swallows exceptions (like an intentional fallback). Returning `False` (or `None`) allows the exception to propagate normally 🛡️. --- ### Interactive Pop-Quiz 🧠 #### What value should `__aexit__()` return if it wants to suppress an exception raised inside the `async with` block? - [ ] `True` (or a truthy value) 🛡️ - [ ] `False` - [ ] `None` - [ ] `StopAsyncIteration` --- ### Practical Challenge 🎯 Build an `AsyncSpan` class that takes a `name`. In `__aenter__`, append `f'ENTER_{name}'` to a list `trace`. In `__aexit__`, append `f'EXIT_{name}'` to `trace`. In `main()`, use `async with AsyncSpan('DB_QUERY'):` and print the resulting `trace`. <details> <summary>Solution</summary> ```python import asyncio trace = [] class AsyncSpan: def __init__(self, name): self.name = name async def __aenter__(self): await asyncio.sleep(0.005) trace.append(f"ENTER_{self.name}") return self async def __aexit__(self, exc_type, exc_val, exc_tb): await asyncio.sleep(0.005) trace.append(f"EXIT_{self.name}") return False async def main(): async with AsyncSpan("DB_QUERY"): trace.append("EXECUTE_SQL") print(trace) asyncio.run(main()) ``` </details>

Checkpoint

What value should `__aexit__()` return if it wants to suppress an exception raised inside the `async with` block? 🧠

Practice

Build an `AsyncSpan` class that takes a `name`. In `__aenter__`, append `f'ENTER_{name}'` to a list `trace`. In `__aexit__`, append `f'EXIT_{name}'` to `trace`. In `main()`, use `async with AsyncSpan('DB_QUERY'):` and print the resulting `trace`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks