Z
ZHANK
编程在线教程Python 教程生成器深度解析
函数与模块

生成器深度解析

yield 原理、send/throw/close、生成器表达式、yield from

生成器深度解析

yield 不只是 return 的替代品——它是协程的基础,支持双向通信、异常传递和委托。

学完本章你将: 掌握 yield/send/throw/close、生成器表达式、yield from。


yield 与 send —— 双向通信

python
def echo():
    while True:
        received = yield          # 右边:接收 send 传来的值
        print(f"收到: {received}")

g = echo()
next(g)          # 启动生成器(推进到第一个 yield)
g.send("Hello")  # 发送值 + 继续执行
g.send("World")
g.close()        # 关闭生成器

throw 与 close

python
def worker():
    try:
        while True:
            yield
    except ValueError:
        print("处理 ValueError")
    finally:
        print("清理资源")

g = worker()
next(g)
g.throw(ValueError)  # 在 yield 处抛出异常
# g.close() 会自动触发 GeneratorExit → finally 执行

yield from —— 委托子生成器

python
def sub_generator():
    yield 1
    yield 2

def main_generator():
    yield 0
    yield from sub_generator()  # 委托——展开子生成器的所有值
    yield 3

print(list(main_generator()))  # [0, 1, 2, 3]

# yield from 也传递 send/throw/close

生成器表达式

python
# 列表推导式(一次性创建)
squares_list = [x*x for x in range(10_000_000)]  # 占用大量内存

# 生成器表达式(惰性求值)
squares_gen = (x*x for x in range(10_000_000))    # 几乎不占内存
print(next(squares_gen))  # 0
print(next(squares_gen))  # 1