Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should a Task be used instead of a coroutine?

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?

like image 938
Rohit Atri Avatar asked Aug 09 '15 13:08

Rohit Atri


1 Answers

"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)

like image 154
Back2Basics Avatar answered Oct 15 '22 11:10

Back2Basics