假设我有一个异步iterable,我可以使用async for
来传递它,然后如何将它映射和过滤到一个新的异步迭代器?下面的代码是我如何对同步iterable执行相同操作的改编,但它不能工作,因为yield
不允许在async def
s中使用
async def mapfilter(aiterable, p, func):
async for payload in aiterable:
if p(payload):
# This part isn't allowed, but hopefully it should be clear
# what I'm trying to accomplish.
yield func(payload)
一个recently published PEP draft (PEP 525),它的支持是scheduled for Python 3.6,它建议允许使用与您所提出的相同语法的异步生成器。在
同时,如果您不想处理异步迭代器样板,也可以使用CryingCyclops在其注释中提到的
asyncio_extras
库。在从the docs:
还有一个async_generator library支持
yield from
构造。在您can't在协程中使用yield。要实现您的想法,我看到的唯一方法是实现Asynchronous Iterator。如果我是对的,像这样:
让我们来测试一下。下面是helper
^{pr2}$arange
类的完整示例(我从here获取):输出:
相关问题 更多 >
编程相关推荐