capypad
0 day streak
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
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import asyncio
 
class AsyncBuffer:
async def __aenter__(self):
print('Opening...')
return self
 
async def __aexit__(self, *args):
print('Closing...')
 
async def __aiter__(self):
for i in range(3):
await asyncio.sleep(0.1)
yield i
 
async 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.