萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 迭代器與生成器深度解析:從協程原理到生產級性能優化

前言:為什麼要深度理解迭代器與生成器?

它們是 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
    

二、生成器:語法糖實現的「可暫停函數」

2.1 生成器函數與生成器表達式

# 生成器函數:含 yield
def fib():
    a, b = 0, 1
    while True:
        yield b
        a, b = b, a + b

# 生成器表達式:類列表推導式但惰性
g = (x * x for x in range(10))   # 

2.2 執行流程圖解

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),而非線程切換。

2.3 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 既是「產出值」也是「接收值」,實現單線程內的協作式多任務。

三、性能與內存對比:列表 vs 生成器

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))
  • 列表:一次性分配所有元素內存,隨機訪問 O(1)。
  • 生成器:常數內存,按需計算,**適合超大/無限序列、管道流式處理**。
  • 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、日誌解析、流式計算。

五、PEP 380: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 優化。

六、生產級最佳實踐清單

  1. 優先生成器表達式:(x for x in src) 替代 [x for x in src],除非需要隨機訪問/多次遍歷。
  2. 文件逐行處理:for line in open('huge.log'): 隱式生成器,常數內存。
  3. 避免在生成器中副作用:yield 前後的副作用(IO、鎖、全局狀態)會在調用者不可控時機執行,導致難以調試。
  4. 異常處理:生成器內部異常會冒泡至調用者 next()/send(),外層需捕獲;finally 確保資源釋放。
  5. 類型提示:from typing import Generator, Iterator; def f() -> Generator[int, None, str]: ... 提升 IDE 支持與靜態檢查。
  6. 異步生成器 (Python 3.6+):async def agen(): yield await fetch() 配合 async for 實現非阻塞流式處理。

七、常見誤區

誤區:「生成器就是線程。」
真相:生成器是單線程內的**協作式調度**,無並行性,切換開銷極低(微秒級),但無法利用多核。CPU 密集任務仍需 multiprocessing 或 concurrent.futures.ProcessPoolExecutor。

結語

迭代器統一了容器訪問接口,生成器將「惰性計算」內化為語法特性,yield from 再構建了協程委托鏈。三者共同構成了 Python **流式處理、異步併發、大數據管道**的核心基礎設施。深度掌握它們,是從「寫腳本」進階為「構建高性能系統」的必經之路。

copyright © 萬盛學電腦網 all rights reserved