10.1 AsyncIterator
비동기 이터레이터 (AsyncIterator)는 요소가 비동기적으로 생성되는 데이터 시퀀스를 처리할 수 있게 해줘. 비동기 함수와 코루틴에서, 예를 들면 네트워크 요청이나 비동기 I/O 작업 등에서 지연되어 받을 수 있는 데이터를 반복할 때 사용해.
비동기 이터레이터
비동기 이터레이터는 두 개의 메서드를 구현해야 해:
메서드 __aiter__():
이 메서드는 자체 비동기 이터레이터를 반환해야 해. 동기 이터레이터의 __iter__() 메서드와 비슷해.
메서드 __anext__():
이 메서드는 다음 값을 비동기적으로 반환하거나 요소가 끝나면 StopAsyncIteration 예외를 발생시켜야 해. 동기 이터레이터의 __next__() 메서드와 비슷해.
예제:
import asyncio
class AsyncIterator:
def __init__(self, start, end):
self.current = start
self.end = end
def __aiter__(self):
return self
async def __anext__(self)(self):
if self.current >= self.end:
raise StopAsyncIteration
await asyncio.sleep(1) # 비동기 지연을 모방
self.current += 1
return self.current
async def main():
async for number in AsyncIterator(1, 5):
print(number)
asyncio.run(main())
비동기 이터레이터는 데이터가 도착하는 대로 처리할 수 있게 해서 다른 작업의 실행을 막지 않아. 네트워크 요청이나 다른 비동기 작업에 특히 유용해.
비동기 이터레이터를 사용하면 데이터를 비동기적으로 처리하는 코드를 더 읽기 쉽고 유지보수하기 쉽게 쓸 수 있어.
10.2 AsyncGenerator
비동기 제너레이터는 async와 await 키워드를 사용해서 비동기적으로 값을 생성할 수 있게 해. 일반 제너레이터와 비슷하지만, 비동기 작업을 수행하기 위해 실행을 일시 중단할 수 있어.
비동기 제너레이터 만들기
비동기 제너레이터는 async def와 yield를 사용해서 정의돼. 비동기 제너레이터는 비동기 작업을 수행하기 위해 내부에서 await를 사용할 수 있어.
예제:
async def async_generator():
for i in range(3):
await asyncio.sleep(1) # 비동기 지연
yield i # 값 생성
비동기 제너레이터 사용하기
비동기 제너레이터는 async for 연산자를 사용해서 비동기 함수 내에서 사용돼.
import asyncio
async def main():
async for value in async_generator():
print(value)
asyncio.run(main())
비동기 제너레이터는 async for라는 간단한 구문을 사용해서 비동기 시퀀스를 처리할 수 있게 해서 코드의 가독성과 유지보수성을 향상시켜.
GO TO FULL VERSION