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