2017-09-29 131 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.