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

関連する問題