python - 用于组合异步迭代器的映射、过滤器和 itertools

标签 python python-3.6 python-asyncio python-itertools

Python 是否支持对异步迭代器进行函数式操作?我知道我可以使用 mapfilteritertools 延迟转换和使用来自普通生成器的数据:

from itertools import accumulate, takewhile

def generator():
    a, b = 1, 1
    while True:
        yield a
        a, b = b, a + b

# create another iterator, no computation is started yet:
another_iterator = takewhile(lambda x: x < 100, accumulate(generator()))
# start consuming data:
print(list(another_iterator))
# [1, 2, 4, 7, 12, 20, 33, 54, 88]

现在,Python 3.6 的异步生成器/迭代器不支持同样的事情,因为它们当然没有实现普通的迭代器协议(protocol):

async def agenerator():
    a, b = 1, 1
    while True:
        yield a
        a, b = b, a + b

accumulate(agenerator())

TypeError: 'async_generator' object is not iterable

是否有某种异步映射或异步 itertools 可以在 Python 3.6/3.7 中实现类似的惰性行为?

最佳答案

我看到的最完整的 itertools 异步版本是 aiostream模块。您的示例将是:

import asyncio
from aiostream.stream import takewhile, accumulate, list as alist


async def agenerator():
    a, b = 1, 1
    while True:
        yield a
        a, b = b, a + b


async def main():
    another_iterator = takewhile(
        accumulate(agenerator()),
        lambda x: x < 100, 
    )

    res = await alist(another_iterator)

    print(res)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

关于python - 用于组合异步迭代器的映射、过滤器和 itertools,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50624170/

相关文章:

python - conda install python=3.6 UnsatisfiableError

php - 我可以使用 mod_vhost_alias 和 mod_wsgi 在同一个 Apache 服务器上运行 PHP 和 Python 吗?

python - 理解Python中的正则表达式分隔符、sub、

python将字典添加到现有字典 - AttributeError : 'dict' object has no attribute 'append'

python - 在推导式中匹配字典键元组项

python - Python 中的 MemoryView 和垃圾收集

Django Channels 在 asyncio.sleep 期间无法接收事件?

python - 尝试在 Atom 中运行 Hydrogen 时如何修复 "NotImplementedError"

python - 遍历 asyncio.coroutine

python - 在运行时更改上传路径 (UPLOAD_FOLDER)