PHpullh
학습 라이브러리/Python/비동기 이터레이터

PYTHON · 비동기

비동기 이터레이터

__aiter____anext__로 비동기 이터레이터 프로토콜을 구현합니다.

비동기고급__aiter____anext__비동기 이터레이터async for

핵심 설명

__aiter____anext__로 비동기 이터레이터 프로토콜을 구현합니다.

Python code

import asyncio

class AsyncCounter:
    """비동기 카운터 이터레이터"""
    def __init__(self, start: int, stop: int):
        self.current = start
        self.stop = stop

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.current >= self.stop:
            raise StopAsyncIteration
        value = self.current
        self.current += 1
        await asyncio.sleep(0.1)  # 비동기 작업
        return value

class AsyncChain:
    """여러 비동기 이터러블을 연결"""
    def __init__(self, *iterables):
        self._iterables = iterables

    def __aiter__(self):
        return self._iterate()

    async def _iterate(self):
        for iterable in self._iterables:
            async for item in iterable:
                yield item

async def main():
    # 기본 사용
    async for num in AsyncCounter(0, 5):
        print(f"  카운트: {num}")

    # 비동기 이터러블 체이닝
    chained = AsyncChain(
        AsyncCounter(0, 3),
        AsyncCounter(10, 13),
    )
    result = [x async for x in chained]
    print(f"체이닝 결과: {result}")

asyncio.run(main())

학습 팁

비동기 이터레이터는 데이터베이스 커서, 페이징 API, 실시간 스트림 처리에 적합합니다.

주의할 점

StopAsyncIteration을 발생시키지 않으면 async for 루프가 끝나지 않습니다.

자주 묻는 질문

비동기 이터레이터란 무엇인가요?

__aiter__ 와 __anext__ 로 비동기 이터레이터 프로토콜을 구현합니다.

비동기 이터레이터 학습 시 주의할 점은 무엇인가요?

StopAsyncIteration 을 발생시키지 않으면 async for 루프가 끝나지 않습니다.