Yield from coroutine vs yield from task

前端 未结 3 1369
孤街浪徒
孤街浪徒 2020-12-13 19:31

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

Tasks vs coroutines

  • Compare:

3条回答
  •  星月不相逢
    2020-12-13 19:59

    As described in PEP 380, the accepted PEP document that introduced yield from, the expression res = yield from f() comes from the idea of the following loop:

    for res in f():
        yield res
    

    With this, things become very clear: if f() is some_coroutine(), then the coroutine is executed. On the other hand, if f() is Task(some_coroutine()), Task.__init__ is executed instead. some_coroutine() is not executed, only the newly created generator is passed as the first argument to Task.__init__.

    Conclusion:

    • res = yield from some_coroutine() => coroutine continues execution and returns the next value
    • res = yield from Task(some_coroutine()) => a new task is created, which stores a non-executed some_coroutine() generator object.

提交回复
热议问题