并发与异步第 17 章预计 19 分钟
本页目录(18 节)

17 · 生成器与协程基础

学完这章,你能用生成器写状态机、惰性管道和无限流,并解释 send、yield from 与 PEP 479 的行为。

本章目标

  • 能解释调用生成器函数为什么「什么都不执行」,以及 yield 如何保留局部状态
  • 能用 send/throw/close 驱动生成器,知道首次必须 send(None)
  • 能用 yield from 做双向委托并接收子生成器的返回值
  • 能复现并修复 PEP 479 的 RuntimeError: generator raised StopIteration
  • 能用生成器搭惰性管道、用 islice 截断无限流
  • 能判断什么时候该用生成器而不是列表

前置知识

  • 第 05 章(迭代协议、生成器表达式)、第 09 章(contextmanager)
  • 熟悉迭代器与 for 的等价展开

从你熟悉的语言出发

概念 C++20 Go Java Rust Python
可恢复函数 coroutine goroutine 无(虚拟线程另说) async/generator generator
暂停/恢复 co_await/co_yield channel 阻塞 无 yield(实验) yield
双向通信 promise channel 无 无 send
委托 手动 channel 转发 无 手动 yield from
惰性序列 range/view channel Stream Iterator generator
一次性 视实现 channel 消费 Stream 一次性 Iterator 一次性 生成器一次性

类比一:生成器是「会暂停的函数」,帧对象留在内存里。 普通函数返回即销毁栈帧;生成器在 yield 处挂起,局部变量、指令位置都保留,下一次 next/send 从那里继续。类似 C++20 协程的挂起点,但语法和调度简单得多。

类比二:yield from 是「生成器层面的代理/转发」。 它把外层的 next/send/throw/close 透传给子生成器,子生成器 return 的值成为 yield from 表达式的结果。类似把请求原样转发给下游服务,再把响应带回。

正文

17.1 调用生成器函数不执行代码

>>> def gen():
...     print("start")
...     yield 1
...     print("resume")
...     yield 2
>>> g = gen()
>>> g
<generator object gen at ...>

调用 gen() 只创建生成器对象,函数体一行都没跑。next(g) 才执行到第一个 yield,打印 start 并返回 1;再 next(g) 从挂起点继续,打印 resume 并返回 2;第三次 next 抛 StopIteration。

yield 既是「产出值」,也是「挂起点」。生成器同时是迭代器:实现 __iter__/__next__,所以能直接用于 for、sum、list。

17.2 send、throw、close

def accumulator():
    total = 0
    while True:
        value = yield total
        if value is None:
            return
        total += value
  • next(g) 等价于 g.send(None):启动到第一个 yield。
  • g.send(x):把 x 作为 yield 表达式的结果,继续执行。
  • 首次启动前 send(非 None) 抛 TypeError,因为还没有 yield 可以接收值。
  • g.throw(E):在挂起点抛异常,生成器可捕获。
  • g.close():在挂起点抛 GeneratorExit,用于清理。

生成器因此是「不对称协程」:调用方可以多次给它送值,但它只能把控制权交回调用方(不能自己调度别的协程)。

17.3 yield from:委托与返回值

def outer():
    result = yield from inner()
    yield result

yield from 做三件事:

  1. 迭代子生成器,把它产出的值原样向上抛。
  2. 把外层的 send/throw/close 透传给子生成器。
  3. 子生成器 return value 时,value 成为 yield from 表达式的结果。

子生成器的返回值存在 StopIteration.value 里;for/list() 会吞掉它,所以需要显式捕获或 yield from。

17.4 PEP 479

生成器内部泄漏的 StopIteration 会被转换成 RuntimeError:

def bad():
    yield 1
    raise StopIteration("boom")

第二次 next 抛 RuntimeError: generator raised StopIteration,原异常作为 __cause__ 保留。

原因:for 依赖 StopIteration 判断迭代结束;如果生成器内部把 StopIteration 当普通异常抛出,会被误认为「正常结束」,悄悄截断数据。PEP 479 让这种错误显式暴露。

正确写法:用 return 结束生成器;在手动 next() 循环里捕获 StopIteration 后 return。

17.5 惰性管道

def numbers(limit):
    yield from range(1, limit + 1)
 
 
def evens(values):
    for value in values:
        if value % 2 == 0:
            yield value
 
 
def squares(values):
    for value in values:
        yield value * value
 
 
stream = squares(evens(numbers(10)))
  • 管道只在被消费时推进;取第一个值只拉到第一个满足条件的元素。
  • 生成器一次性:list(stream) 之后不能重放,需要重新创建。
  • 适合大文件/大流:峰值内存与「当前元素」同量级,而不是整条序列。

17.6 无限流与 islice

from itertools import cycle, islice
 
colors = cycle(["r", "g", "b"])
list(islice(colors, 7))
  • cycle/自写 while True: yield 可以表示无限序列。
  • 必须用 islice、takewhile 或 break 限界;直接 list()/sum() 会永不返回。
  • 生成器有状态:取完 7 个后再取 2 个,会从第 8 个继续。

17.7 生成器表达式与 contextmanager

  • 生成器表达式 (x * x for x in xs) 是惰性、一次性的,适合直接传给 sum/any/join。
  • 嵌套生成器表达式要小心求值顺序:外层 for 先、内层后。
  • contextlib.contextmanager 的本质是「只 yield 一次的生成器」:yield 前是 __enter__,之后是 __exit__(第 09 章)。

报错现场

场景一:首次 send 非 None。

Traceback (most recent call last):
  File "/tmp/send_err.py", line 5, in <module>
    g.send(1)
TypeError: can't send non-None value to a just-started generator
  • 生成器还没执行到任何 yield,没有表达式可以接收 1。
  • 修法:先 next(g) 或 g.send(None) 启动。

场景二:PEP 479。

Traceback (most recent call last):
  File "/tmp/pep479_err.py", line 3, in bad
    raise StopIteration("boom")
StopIteration: boom
 
The above exception was the direct cause of the following exception:
 
Traceback (most recent call last):
  File "/tmp/pep479_err.py", line 7, in <module>
    next(g)
RuntimeError: generator raised StopIteration
  • 第一段是生成器内部抛出的 StopIteration。
  • direct cause 表明 RuntimeError 是由它触发的。
  • 修法:把 raise StopIteration 改成 return;手动迭代时捕获后 return。

反直觉差异:调用生成器函数不执行,生成器只能消费一次

你的直觉:gen() 会立刻执行函数体;生成器像列表一样可以反复遍历。

实际行为:

  1. gen() 只创建生成器对象,函数体在第一次 next 时才运行到第一个 yield。
  2. 生成器是迭代器,iter(gen) is gen;遍历一次后耗尽,第二次 for 得到空。
  3. list(gen)/sum(gen) 会消费掉它;需要重放必须重新调用生成器函数。
  4. yield from 会把 send 透传给子生成器;外层不需要手动转发。

为什么这样设计:生成器用「挂起帧」实现惰性与常量内存;如果允许重放,就必须缓存所有产出,退化成列表。一次性语义也让它能安全表示流/文件/网络数据。

正确写法:

  • 需要多次遍历时,把生成器函数调用放进循环/函数,每次新建。
  • 需要缓存时显式 list(),并接受内存成本。
  • 管道设计成「输入 → 输出」纯惰性链,不要在中间阶段重复消费同一个生成器。

性能与复杂度

方式(1000 万项求和) 实测(3.12.9 / macOS arm64) 峰值内存
sum(range(N)) 6.3 ms 极低(range 惰性)
sum(gen()) 16.7 ms 0.3 KiB
sum(list(range(N))) 11.5 ms 38.1 MiB

生成器比列表慢约 45%(多一层 yield 调度),但内存从 38 MiB 降到不到 1 KiB。数据量越大,内存优势越明显;如果后续还要多次随机访问,列表更合适。

示例索引

目录 演示什么 预期看到
examples/17-generators-coroutines/01-generator-state-machine/ send 驱动累加器 0 → 5 → 12、首次 send 报错
examples/17-generators-coroutines/02-yield-from-delegation/ 委托与返回值 inner-done:x、stop: outer-done
examples/17-generators-coroutines/03-pep479-stopiteration/ PEP 479 RuntimeError: generator raised StopIteration
examples/17-generators-coroutines/04-generator-pipeline/ 三阶段惰性管道 after first: [1, 2]、sum: 220
examples/17-generators-coroutines/05-infinite-stream/ cycle + islice 前 7 个颜色、计数器前 5 项

练习题

  1. 实现 running_total():send 驱动累计值。见 exercises/17/01-send-running-total/。
  2. 实现 flatten(nested):用 yield from 递归展平 list/tuple。见 exercises/17/02-flatten-yield-from/。
  3. 实现 safe_consume(values):手动 next 循环,PEP 479 安全地结束。见 exercises/17/03-safe-consume/。
  1. total = 0;while True: value = yield total; if value is None: return; total += value。
  2. 遍历元素,遇到 list/tuple 就 yield from flatten(item),否则 yield item。
  3. while True: try: value = next(values) except StopIteration: return; yield value。

章末自检

  1. 调用生成器函数时执行了什么?第一次 next 执行到哪?
  2. send/throw/close 各做什么?首次为什么只能 send(None)?
  3. yield from 的三件事是什么?子生成器的返回值去哪了?
  4. PEP 479 解决什么问题?正确写法是什么?
  5. 生成器为什么只能消费一次?需要重放怎么办?
  6. 惰性管道的峰值内存为什么低?
  7. 无限流如何安全截断?
  8. contextmanager 与生成器是什么关系?
  1. 只创建生成器对象;第一次 next 运行到第一个 yield。
  2. 送值/抛异常/关闭;首次还没有 yield 表达式接收值。
  3. 迭代子生成器、透传 send/throw/close、接收 return 值;值存在 StopIteration.value。
  4. 防止内部 StopIteration 被误判为迭代结束;用 return 或捕获后 return。
  5. 迭代器状态只保留当前位置;重新调用生成器函数创建新实例。
  6. 只保留当前元素与少量帧状态,不物化整条序列。
  7. islice/takewhile/显式 break。
  8. contextmanager 把单次 yield 的生成器包装成 __enter__/__exit__。

延伸阅读

  • The Python Tutorial §9.9 Generators
  • The Python Language Reference §6.2.9 Yield expressions、§6.2.9.1 Generator-iterator methods
  • The Python Standard Library §10.1 itertools(islice、cycle、chain)
  • PEP 255 Simple Generators
  • PEP 342 Coroutines via Enhanced Generators
  • PEP 380 Syntax for Delegating to a Subgenerator
  • PEP 479 Change StopIteration handling inside generators