Junior — Middle
How do the implementations of asynchronous and synchronous context managers differ in Python?
sobes.tech AI
Answer from AI
A synchronous context manager implements the __enter__ and __exit__ methods, which are called when entering and exiting a with block. It is used for resource management in synchronous code.
An asynchronous context manager implements the __aenter__ and __aexit__ methods, which return awaitable objects and are used with async with in asynchronous code. This allows proper management of resources that require asynchronous release or initialization.
Example of a synchronous manager:
class SyncManager:
def __enter__(self):
print('Enter sync')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('Exit sync')
with SyncManager():
print('Inside sync')
Example of an asynchronous manager:
class AsyncManager:
async def __aenter__(self):
print('Enter async')
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
print('Exit async')
import asyncio
async def main():
async with AsyncManager():
print('Inside async')
asyncio.run(main())
The key difference is the methods and syntax (with vs async with), which allow proper handling of asynchronous operations within the manager.