Can anyone provide practical advice on how to choose between python asyncio module's Tasks and Coroutines?
If I were to achieve something asynchronously, I could do either of the 2 below -
import asyncio
@asyncio.coroutine
def print_hello():
print('Hello')
loop = asycio.get_event_loop()
loop.run_until_complete(print_hello)
loop.close()
OR
import asyncio
@asyncio.coroutine
def print_hello():
print('Hello')
print_task = asyncio.ensure_future(print_hello)
loop = asycio.get_event_loop()
loop.run_until_complete(asyncio.wait_for(print_task))
loop.close()
What factors decide which of the 2 methods above to choose?
"Generally you would use a coroutine when you want to directly couple it to the calling parent coroutine using yield from. This coupling is what drives the child coroutine and forces the parent coroutine to wait for the child coroutine to return prior to continuing. A Task, on the other hand, doesn't have to be driven by a parent coroutine because it can drive itself." - shongololo
(Please don't answer things in the comments)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With