본문 바로가기

라이브러리

[Python] aiter() 함수 사용법

aiter() 에 대하여 자세하게 알아봅시다

aiter()

aiter() 함수는 Python 3.10부터 도입된 비동기(iterable)의 이터레이터를 반환해주는 내장 함수입니다.
주로 async for 반복문에서 사용되는 비동기 객체(asynchronous iterable)를 이터레이션 하고 싶을 때 사용합니다. 동기 버전인 iter()와 유사하지만, 비동기 iterable만 지원합니다.

시그니처:

aiter(async_iterable)
  • async_iterable: 비동기 이터러블(예: 비동기 제너레이터, 비동기 클래스 등)

기본 사용법 예시

1. 비동기 제너레이터에 aiter() 사용

async def agen():
    yield 1
    yield 2
    yield 3

ait = aiter(agen())
print(type(ait))  # <class 'async_generator'>

2. async for문에서 활용

async def agen():
    yield 'a'
    yield 'b'

ait = aiter(agen())
async for v in ait:
    print(v)

3. 비동기 이터러블 커스텀 클래스에서 사용

class AsyncIterable:
    def __aiter__(self):
        self.i = 0
        return self
    async def __anext__(self):
        if self.i < 3:
            self.i += 1
            return self.i
        else:
            raise StopAsyncIteration

ait = aiter(AsyncIterable())
async for v in ait:
    print(v)

고급 사용법 예시

1. 비동기 파일 라인 단위 반복

import aiofiles

async def read_file():
    async with aiofiles.open('test.txt') as f:
        ait = aiter(f)
        async for line in ait:
            print(line.strip())

2. 비동기 이터레이터에서 직접 anext()와 조합

async def agen():
    for i in range(3):
        yield i

ait = aiter(agen())
print(await anext(ait))  # 0
print(await anext(ait))  # 1

3. asyncio.gather와 조합

import asyncio

async def agen():
    for i in range(5):
        yield i

async def consume():
    ait = aiter(agen())
    async for item in ait:
        print(item)

asyncio.run(consume())

총평

aiter()는 Python의 비동기 프로그래밍에서 비동기 이터러블 객체를 다룰 때 매우 간편하게 사용할 수 있는 함수입니다. 특히, 비동기 제너레이터나 비동기형 커스텀 클래스와 함께 자주 쓰이며, 코드의 가독성과 일관성을 높여줍니다. 동기 iter()와 매우 유사한 역할을 하므로, 비동기 I/O 또는 코루틴 기반의 반복 작업이 필요할 때 메모해두면 좋습니다.