python / expert
Snippet
Async Iteration with Context Managers
This demonstrates combining asynchronous context managers (__aenter__/__aexit__) with asynchronous iterators (__aiter__). It allows for safe resource management in concurrent environments while processing streams of data asynchronously using 'async with' and 'async for'.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import asyncioclass AsyncBuffer:async def __aenter__(self):print('Opening...')return selfasync def __aexit__(self, *args):print('Closing...')async def __aiter__(self):for i in range(3):await asyncio.sleep(0.1)yield iasync def main():async with AsyncBuffer() as buf:async for item in buf:print(item)
Breakdown
1
async def __aenter__(self):
Asynchronous setup method for the 'async with' block.
2
async def __aiter__(self):
Defines the object as an asynchronous iterator.
3
yield i
Asynchronously produces a value for the 'async for' loop.