It is not possible to link your own asynchronous coroutines simply by returning them

I use coroutines based on the py3.4 generator, and in several places I fetched them, just having one coroutine call return inner_coroutine()(as in the example below). However, I am now converting them to use my own coroutines py3.5, and I found that it no longer works, since the internal coroutine does not start (see the output from the example below). To start the internal internal coroutine, I need to use return await inner_coroutine()instead of the original return inner_coroutine().

I expected that linking my own coroutines would work the same way as on the basis of the generator, and could not find any documentation that said otherwise. Am I missing something or is this the actual limitation of native coroutines?

import asyncio

@asyncio.coroutine
def coro():
    print("Inside coro")

@asyncio.coroutine
def outer_coro():
    print("Inside outer_coro")
    return coro()

async def native_coro():
    print("Inside native_coro")

async def native_outer_coro():
    print("Inside native_outer_coro")
    # return await native_coro()  # this works!
    return native_coro()

loop = asyncio.get_event_loop()
loop.run_until_complete(outer_coro())
loop.run_until_complete(native_outer_coro())

:

Inside outer_coro
Inside coro
Inside native_outer_coro
foo.py:26: RuntimeWarning: coroutine 'native_coro' was never awaited
loop.run_until_complete(native_outer_coro())
+2
2

, , , , , .

, python , - , yield. @asyncio.coroutine. , , next , , yield statement. , - . , . , ,

    return await inner_coroutine()

, . , , , , . .

+1

- . .

:

c = coro_func()     # create coroutine object
coro_res = await c  # await this object to get result

...

@asyncio.coroutine
def outer():
    return inner()

... outer() inner() coroutine, . - inner() (, yield from inner()).

asyncio , : coroutine . coroutine ( ), .

, :

loop = asyncio.get_event_loop()
print('old res:', loop.run_until_complete(outer_coro()))
print('new res:', loop.run_until_complete(native_outer_coro()))
+1

Source: https://habr.com/ru/post/1688754/


All Articles