【问题标题】:Asynchronous generator functions in PythonPython中的异步生成器函数
【发布时间】:2020-11-20 18:43:09
【问题描述】:

考虑 Python 文档中的 this example

def gen(): # defines a generator function
  yield 123


async def agen(): # defines an asynchronous generator function
  yield 123

我知道这个例子很简单,但是我可以gen做什么而不能agen做些什么,反之亦然?我会以什么方式注意到它们的不同?

相关:

我认为这个问题会有所帮助,但我仍然不明白: What are the differences between the purposes of generator functions and asynchronous generator functions

【问题讨论】:

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


    【解决方案1】:

    一个适合 async/await 框架,另一个不适合。

    首先,常规生成器函数。这里没有协同多任务处理:

    def f():
        return 4
    
    
    def g():
        return 5
    
    
    def gen():
        """cannot call async functions here"""
        yield f()
        yield g()
    
    
    def run():
        for v in gen():
            print(v)
    

    vs 下面,with 协作式多任务处理。允许其他任务在await/during async for之后运行

    async def f():
        return 4
    
    
    async def g():
        return 5
    
    
    async def gen():
        """can await async functions here"""
        yield await f()
        yield await g()
    
    
    async def run():
        async for v in gen():
            print(v)
    
    
    asyncio.run(run())
    

    【讨论】:

    • 谢谢! QQ:为什么第一种情况不能调用异步函数,第二种情况可以?那是因为只有异步函数才能调用异步函数吗?
    • 是的,没错!在第一种情况下,您不是在事件循环的上下文中执行,因此您不能“等待”(即,将控制权传递回事件循环)。
    猜你喜欢
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 2015-11-29
    • 2017-12-06
    • 1970-01-01
    • 2023-04-10
    • 2021-07-04
    • 1970-01-01
    相关资源
    最近更新 更多