Python & FastAPI•Part 3: Asynchronous Programming & Concurrency (26 - 40)
Async Context Managers & Async Iterators:
In Simple Words:
- Async Context Manager: Implements
__aenter__and__aexit__withasync with. - Async Iterator: Implements
__aiter__and__anext__withasync for.
python
class AsyncStreamer:
def __aiter__(self):
self.count = 0
return self
async def __anext__(self):
if self.count >= 3: raise StopAsyncIteration
await asyncio.sleep(0.1)
self.count += 1
return self.count
async def test_stream():
async for item in AsyncStreamer():
print(item)