DEV Community

qing
qing

Posted on

TIL: Context Managers Work With async/await in Python (2026)

TIL: Context Managers Work With async/await in Python

When working with asynchronous code in Python, it's essential to manage resources efficiently. Context managers, introduced in Python 3.7, can be used with async/await to ensure that resources are properly cleaned up after use.

The async with statement allows you to use context managers with asynchronous code. You can create an asynchronous context manager using the @contextlib.asynccontextmanager decorator.

Here's a minimal example of an asynchronous context manager that connects to a database:

import asyncio
import contextlib

@contextlib.asynccontextmanager
async def connect_to_database():
    # Establish a database connection
    print("Connecting to database...")
    await asyncio.sleep(1)  # Simulate connection time
    try:
        yield
    finally:
        # Close the database connection
        print("Disconnecting from database...")
        await asyncio.sleep(1)  # Simulate disconnection time

async def main():
    async with connect_to_database():
        print("Querying database...")

asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

In this example, the connect_to_database context manager establishes a database connection when entering the async with block and closes it when exiting.

The key takeaway is that using async with and @contextlib.asynccontextmanager allows you to write asynchronous code that is both efficient and easy to read, ensuring that resources are properly cleaned up after use.


Follow me on Dev.to for daily Python tips and quick guides!


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*

Top comments (0)