yield 關鍵字包含 yield 的函數稱為生成器函數,調用它返回生成器對象而非執行函數體:
def gen_012():
yield 0
yield 1
yield 2
g = gen_012() #
print(next(g)) # 0
print(next(g)) # 1
print(next(g)) # 2
next(g) # StopIteration
next() → 從函數開頭執行至首個 yield,暫停並返回值。next() → 從上次暫停處恢復,執行至下一個 yield。return 或落底) → next() 拋出 StopIteration。def fibonacci():
a = b = 1
yield a
yield b
while True:
a, b = b, a + b
yield b
# 使用:打印斐波那契數列前 10 項
for i, num in enumerate(fibonacci()):
if i >= 10: break
print(num, end=' ')
# 1 1 2 3 5 8 13 21 34 55
無限循環因 yield 暫停而安全,實現了惰性無限序列。
return 返回值嗎?return(SyntaxError)。可用裸 return 提前結束生成器。try...finally 中 yield 行為?finally 塊在生成器真正結束時執行(垃圾回收或顯式 close()),而非每次 yield 暫停時。這保證了資源釋放邏輯正確運行。yield from subgen()(PEP 380),自動處理雙向通信與異常傳播。生成器新增方法使其成為協程(協作式多任務):
| 方法 | 作用 |
|---|---|
send(value) | 恢復生成器,yield 表達式的值為 value。首次調用需 send(None) 或 next()。 |
throw(type, val, tb) | 在生成器暫停處拋出異常。 |
close() | 關閉生成器,內部拋出 GeneratorExit,觸發 finally。 |
def task(name):
for i in range(3):
print(f"{name}: step {i}")
yield # 主動讓出控制權
def scheduler(tasks):
while tasks:
for t in list(tasks):
try:
next(t)
except StopIteration:
tasks.remove(t)
t1 = task("A")
t2 = task("B")
scheduler([t1, t2])
# 輸出交替: A:0, B:0, A:1, B:1, A:2, B:2
# pip install pipe
from pipe import select, where, chain
result = range(10) \
| where(lambda x: x % 2 == 0) \
| select(lambda x: x ** 2) \
| chain(list)
print(result) # [0, 4, 16, 36, 64]
pipe 將生成器鏈式操作變為可讀的管道語法,適合數據清洗、ETL 等場景。
yield)。send/throw/close/yield from)。pipe 提供更聲明式的管道語法。