它們是 Python 惰性計算、流式處理、協程併發的基石。掌握其內部機制,能寫出內存常數級、啟動極快、支持無限序列的高性能代碼;也是理解 async/await、contextlib、asyncio 底層邏輯的前置知識。
class Iterator:
def __iter__(self): return self # 返回迭代器自身
def __next__(self): # 返回下一個元素或拋 StopIteration
...
__iter__ 返回迭代器(如 list, dict, file)。__iter__ 和 __next__。for x in obj 語法糖等價於:
it = iter(obj) # obj.__iter__()
while True:
try:
x = next(it) # it.__next__()
except StopIteration:
break
# loop body
# 生成器函數:含 yield
def fib():
a, b = 0, 1
while True:
yield b
a, b = b, a + b
# 生成器表達式:類列表推導式但惰性
g = (x * x for x in range(10)) #
def gen():
print("start")
yield 1
print("middle")
yield 2
print("end")
g = gen() # 不執行任何打印,返回 generator object
next(g) # → print("start") → yield 1 → 暫停
next(g) # → print("middle") → yield 2 → 暫停
next(g) # → print("end") → 拋 StopIteration
本質:生成器是一種**棧幀可保存、可恢復的函數**,由 Python 解釋器在 C 層維護幀對象 (PyGenObject),而非線程切換。
send() / throw() / close():雙向通信與控制def psychologist():
print("Please tell me your problems")
while True:
answer = (yield) # 接收 send() 傳入的值
if answer is not None:
if answer.endswith('?'):
print("Don't ask yourself too much questions")
elif 'good' in answer:
print("A that's good, go on")
elif 'bad' in answer:
print("Don't be so negative")
free = psychologist()
next(free) # 啟動到第一個 yield
free.send('I feel bad') # 傳值並恢復執行
free.send("Why I shouldn't?")
free.close() # 拋 GeneratorExit 於 yield 處,觸發 finally
這正是**協程**雛形:yield 既是「產出值」也是「接收值」,實現單線程內的協作式多任務。
import sys
L = [x * x for x in range(10_000_000)] # ~360 MB
G = (x * x for x in range(10_000_000)) # ~112 bytes (生成器對象)
print(sys.getsizeof(L), sys.getsizeof(G))
itertools.islice、itertools.chain 組合生成器構建高效數據管道。def source(nums):
for n in nums:
yield n
def filter_even(it):
for x in it:
if x % 2 == 0:
yield x
def square(it):
for x in it:
yield x * x
def take(n, it):
for i, x in enumerate(it):
if i >= n: break
yield x
# 組合:取前 5 個偶數的平方
pipeline = take(5, square(filter_even(source(range(100)))))
print(list(pipeline)) # [0, 4, 16, 36, 64]
每層只持有上游迭代器引用,**無中間列表分配**,極適合 ETL、日誌解析、流式計算。
yield from 委托生成器def subgen():
yield 1
yield 2
return "done"
def delegator():
result = yield from subgen() # 自動雙向通道,含異常/返回值傳遞
print("subgen returned:", result)
g = delegator()
list(g) # [1, 2] 並打印 "subgen returned: done"
StopIteration 並提取 value 屬性。asyncio 內部大量使用 yield from 實現協程委托(Python 3.4-3.10),3.11+ 改用 C 級 PyGen_Send 優化。(x for x in src) 替代 [x for x in src],除非需要隨機訪問/多次遍歷。for line in open('huge.log'): 隱式生成器,常數內存。yield 前後的副作用(IO、鎖、全局狀態)會在調用者不可控時機執行,導致難以調試。next()/send(),外層需捕獲;finally 確保資源釋放。from typing import Generator, Iterator; def f() -> Generator[int, None, str]: ... 提升 IDE 支持與靜態檢查。async def agen(): yield await fetch() 配合 async for 實現非阻塞流式處理。誤區:「生成器就是線程。」
真相:生成器是單線程內的**協作式調度**,無並行性,切換開銷極低(微秒級),但無法利用多核。CPU 密集任務仍需multiprocessing或concurrent.futures.ProcessPoolExecutor。
迭代器統一了容器訪問接口,生成器將「惰性計算」內化為語法特性,yield from 再構建了協程委托鏈。三者共同構成了 Python **流式處理、異步併發、大數據管道**的核心基礎設施。深度掌握它們,是從「寫腳本」進階為「構建高性能系統」的必經之路。