Gill Bates Gill Bates - 1 year ago 93
Python Question

Yield from coroutine vs yield from task

Guido van Rossum, in his speech in 2014 on Tulip/Asyncio shows the slide:

Tasks vs coroutines

  • Compare:

    • res = yield from some_coroutine(...)

    • res = yield from Task(some_coroutine(...))

  • Task can make progress without waiting for it

    • As log as you wait for something else

      • i.e. yield from

And I'm completely missing the point.

From my point of view both constructs are identical:

I case of bare coroutine - it gets scheduled, so the task is created anyways, because scheduler operates with Tasks, then coroutine caller coroutine is suspended until callee is done and then becomes free to continue execution.

In case of Task - all the same - new task is schduled and caller coroutine waits for its completion.

What is the difference in the way that code executed in both cases and what impact it has that developer should consider in practice?


Links to authoritative sources (GvR, PEPs, docs, core devs notes) will be very appreciated.

Answer Source

For the calling side co-routine yield from coroutine() feels like a function call (i.e. it will again gain control when coroutine() finishes).

yield from Task(coroutine()) on the other hand feels more like creating a new thread. Task() returns almost instantly and very likely the caller gains control back before the coroutine() finishes.

The difference between f() and th = threading.Thread(target=f, args=()); th.start(); th.join() is obvious, right?