2017-09-29 134 views
0

如果我尝试运行在Python下面的代码,我得到以下错误:如何从Python中的异步函数中访问返回值?

async def foo(): 
    yield 1 

async def bar(): 
    x = await foo() 
b=bar() 
b.send(None) 

TypeError: object async_generator can't be used in 'await' expression

在另一方面,下面的代码工作(并抛出一个StopIteration,但预计):

async def foo(): 
    pass 

async def bar(): 
    await foo() 
b=bar() 
b.send(None) 

为什么不能正常工作?

我可以,如果我将其替换foo它的工作:

@coroutine 
def foo(): 
    yield 1 

这里的问题是,这似乎很奇怪,我敢肯定这是不是让这种行为的推荐方式。然后在大多数语言中,您只需要异步并等待,而不是@coroutine呢!

回答

1

我在这里假设您正在使用asyncio库。
我认为使用装饰@coroutine的建议与async def功能兼容性的原因,

although this is not strictly enforced.

asyncio.coroutine documentation

而且

@asyncio.coroutine Decorator to mark generator-based coroutines. This enables the generator use yield from to call async def coroutines, and also enables the generator to be called by async def coroutines, for instance using an await expression.

There is no need to decorate async def coroutines themselves.