如何实现异步迭代器和异步生成器?
进阶
答题要点
import asyncio
from typing import AsyncIterator
# 异步迭代器类
class AsyncDataReader:
def __init__(self, data_source):
self.source = data_source
self.index = 0
def __aiter__(self):
return self
async def __anext__(self):
if self.index >= len(self.source):
raise StopAsyncIteration
await asyncio.sleep(0.1) # 模拟异步IO
item = self.source[self.index]
self.index += 1
return item
# 使用异步迭代器
async def process_data():
reader = AsyncDataReader([1, 2, 3, 4, 5])
async for item in reader:
print(f"Processing: {item}")
# 异步生成器
async def async_data_stream(urls: list) -> AsyncIterator[dict]:
import aiohttp
async with aiohttp.ClientSession() as session:
for url in urls:
async with session.get(url) as response:
data = await response.json()
yield data
async def consume_stream():
async for data in async_data_stream(['http://api1', 'http://api2']):
print(data)
# 异步生成器发送值
async def async_accumulator():
total = 0
while True:
value = yield total
if value is None:
break
total += value
async def use_accumulator():
acc = async_accumulator()
await acc.asend(None) # 启动
result = await acc.asend(10)
print(result) # 10
result = await acc.asend(20)
print(result) # 30
# 异步列表推导
async def async_comprehension():
# 异步列表推导
results = [item async for item in async_data_stream(urls)]
# 异步生成器表达式
gen = (item async for item in async_data_stream(urls))
# 配合await
results = [await process(item) async for item in async_data_stream(urls)]
# 并发处理异步迭代器
async def process_concurrently(async_iter, concurrency=10):
semaphore = asyncio.Semaphore(concurrency)
async def process_with_limit(item):
async with semaphore:
return await process(item)
tasks = []
async for item in async_iter:
task = asyncio.create_task(process_with_limit(item))
tasks.append(task)
return await asyncio.gather(*tasks)
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题