12

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?

Rohit Atri
  • 231
  • 1
  • 10
  • 4
    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. – songololo Aug 09 '15 at 16:25
  • Does [this question](http://stackoverflow.com/q/27076577/2073595) answer your question in a satisfactory way? I'm tempted to mark this one as a dupe, but let me know if you're looking for additional information. – dano Aug 09 '15 at 17:39
  • 1
    Also, `loop.run_until_complete(coro)` always converts `coro` into a `Task` internally; you need at least one `Task` to drive the program. – dano Aug 09 '15 at 17:39
  • @dano The other question has a good theoretical discussion - thanks! The intention of this question was to get to know the practical scenarios where one method can/should be used in preference over the other - from practical experience, of course. – Rohit Atri Aug 17 '15 at 04:55
  • `Task` offers fine control like cancellation and inspecting stack frames. I suggest using `coroutine` if possible, which helps keep logic simple and clean. – Huazuo Gao Sep 20 '15 at 05:16
  • 1
    Possible duplicate of [Difference between coroutine and future/task in Python 3.5?](http://stackoverflow.com/questions/34753401/difference-between-coroutine-and-future-task-in-python-3-5) – Bharel Apr 18 '16 at 13:14

1 Answers1

1

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

Back2Basics
  • 7,406
  • 2
  • 32
  • 45