【问题标题】:Other ways to get the return values from "yield" in "async" functions in Python?在 Python 的“异步”函数中从“yield”获取返回值的其他方法?
【发布时间】:2022-11-08 03:13:50
【问题描述】:

使用时async for声明async def call_test() 中如下图:

import asyncio

async def test():
    yield "One"
    yield "Two"
    yield "Three"

async def call_test():
    async for i in test(): # Here
        print(i)

asyncio.run(call_test())

我可以在async def test() 中从yield 获得以下返回值:

One
Two
Three

现在,还有其他类似下面的方法可以从yield 中的async def test() 中获取返回值吗?没关系,如果其他方式不如下,只要我们可以从async def test()中的yield获取返回值即可:

# ...

async def call_test():
    x = test()
    print(next(x)) # "One"
    print(next(x)) # "Two"
    print(next(x)) # "Three"

# ...
# ...

async def call_test():
    x = test()
    print(x.__next__()) # 'One"
    print(x.__next__()) # "Two"
    print(x.__next__()) # "Three"

# ...

【问题讨论】:

    标签: python python-3.x asynchronous python-asyncio python-yield


    【解决方案1】:

    对于异步生成器,您必须等待内置的 anext 而不是调用 next

    ...
    print(await anext(x))
    ...
    

    【讨论】:

      猜你喜欢
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 2017-05-22
      • 2019-12-29
      • 2015-12-03
      相关资源
      最近更新 更多