【发布时间】:2021-04-09 08:09:10
【问题描述】:
取以下两个函数:
import asyncio
def a():
for index in range(2):
# Capture `index` as `local_index` in case awaiting is postponed.
async def next_index(local_index=index):
# Simulate network request.
await asyncio.sleep(0)
return local_index
yield next_index()
async def b():
for index in range(2):
# Simulate network request.
await asyncio.sleep(0)
yield index
a 返回一个Iterable[Awaitable[int]]。 b 返回一个 AsyncIterable[int]。两者的迭代都可以这样完成:
async def main():
for index in a():
print(await index)
async for index in b():
print(index)
asyncio.run(main())
输出:
0
1
0
1
上述示例的关键是我能够在没有外部 async 的情况下生成 Awaitables,因为内部函数是 async。
- 就功能而言,
AsyncIterable[T]是否允许Iterable[Awaitable[T]]提供任何功能?
我还有一个非常相关的问题。来自PEP 492 - Asynchronous Iterators and "async for":
异步迭代器对象必须实现 anext 方法 (或者,如果使用 CPython C API 定义,则为 tp_as_async.am_anext 插槽) 返回一个可等待的。
- 由于不需要外部
async来产生Awaitables,__anext__是否提供优于同步__next__返回Awaitables 的专有功能?
这可能是我遗漏的地方,但根据我目前的理解,异步协议和StopAsyncIteration 看起来可以使用同步协议和StopIteration 来模仿它们(当然不那么简洁)。
【问题讨论】:
标签: python asynchronous async-await generator python-asyncio