【问题标题】:How to use asynchronous generator in Python 3.6?如何在 Python 3.6 中使用异步生成器?
【发布时间】:2019-02-25 01:15:47
【问题描述】:

我需要处理来自服务器的几页数据。我想像这样为它制作一个生成器。不幸的是我得到TypeError: 'async_generator' object is not iterable

async def get_data():
    i = 0
    while i < 3:
        i += 1
        data = await http_call()  # call to http-server here
        yield data

data = [i for i in get_data()]  # inside a loop

下一个变种引发TypeError: object async_generator can't be used in 'await' expression

data = [i for i in await get_data()]  # inside a loop

【问题讨论】:

    标签: python python-3.x async-await generator


    【解决方案1】:

    在您的理解中使用async for。见PEP 530 -- Asynchronous Comprehensions

    data = [i async for i in get_data()]
    

    根据您使用的 Python 版本,这可能仅在 async def 函数中可用。

    【讨论】:

    • 请注意,这不会对所有页面进行异步调用。
    • @Aaron_ab 你是什么意思?
    • 如果我们记录对 get_data 的每次访问,在开始和结束时,我们会看到 get_data1 将开始和结束,然后是 get_data2 等等......没有并发
    • async 并不意味着抢占式多线程中的“并发”。多亏了 GIL,在纯 Python 级别没有抢占式多线程。 async 表示 cooperative multitasking,这意味着开发人员在每个 await 表达式中明确放弃对其他当前暂停的协程和异步生成器的控制。在没有显式多线程或多处理的情况下,异步生成器仍然按顺序(即非并发)产生结果。
    • 如果您想在异步范式下实现真正的并发,请考虑将 the asyncio.Queue classasyncio.as_completed() function 用于 I/O 绑定操作 the async.run_in_executor() function 用于 CPU 绑定操作而是。
    猜你喜欢
    • 2019-04-12
    • 2017-05-12
    • 2017-05-12
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 2021-11-19
    • 2020-11-20
    • 2016-08-21
    相关资源
    最近更新 更多