laixintao / problems

❓See issues.
0 stars 0 forks source link

为什么需要yield from? #8

Closed laixintao closed 6 years ago

laixintao commented 6 years ago

pep 380

laixintao commented 6 years ago

直接每一次 term = yield average 就可以,为什么非要产生异常,通过异常传递result?

可能如果不终止协程,会导致内存泄露?

laixintao commented 6 years ago

yield from 可用于简化for循环中的yield表达式。

例如:

def gen(): for c in 'AB': yield c for i in range(1, 3): yield i

list(gen()) ['A', 'B', '1', '2'] 可以改写为:

def gen(): yield from 'AB' yield from range(1, 3)

laixintao commented 6 years ago

其实就是一个语法糖,使 yield 的coroutine重构成为可能。

PEP380中有两段代码,一段是用 yield from 的,一段没有用。

如果没有用,将要自己实现管道,传递返回值、异常等。