InterviewHubPRO
Section Overview
Q31

Question 31 of 65

Part 3: Asynchronous Programming & Concurrency (26 - 40)

48%
Python & FastAPI•Part 3: Asynchronous Programming & Concurrency (26 - 40)

Async Context Managers & Async Iterators:

In Simple Words:

  • Async Context Manager: Implements __aenter__ and __aexit__ with async with.
  • Async Iterator: Implements __aiter__ and __anext__ with async 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)