The difference is if you have a yield statement or not.
Here's the code:
from types import coroutine as t_coroutine
from asyncio import coroutine as a_coroutine, ensure_future, sleep, get_event_loop
@a_coroutine
def a_sleep():
print("doing something in async")
yield 1
@t_coroutine
def t_sleep():
print("doing something in types")
yield 1
async def start():
sleep_a = a_sleep()
sleep_t = t_sleep()
print("Going down!")
loop = get_event_loop()
loop.run_until_complete(start())
In this example everything seem same - here's the debugging info from pycharm (we're standing on the "Going down!" line). Nothing is printed in console yet, so the functions didn't start yet.
But if we remove the yield
, the types
version will start function instantly!
from types import coroutine as t_coroutine
from asyncio import coroutine as a_coroutine, ensure_future, sleep, get_event_loop
@a_coroutine
def a_sleep():
print("doing something in async")
@t_coroutine
def t_sleep():
print("doing something in types")
async def start():
sleep_a = a_sleep()
sleep_t = t_sleep()
print("Going down!")
loop = get_event_loop()
loop.run_until_complete(start())
Now we have doing something in types
in console printed. And here's the debug info:
As you can see it starts right after call, if there is no result and returns None.
As for usage, you should use asyncio
version always. If you need to run it like fire and forget (running instantly and getting results later) - use ensure_future
function.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…