萬盛學電腦網

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

Python try/finally/with 資源管理完全指南:從檔案操作到自定義上下文管理器

資源釋放(檔案、鎖、連線、臨時檔)是程式健壯性的生命線。Python 透過 try/finally 與 with(上下文管理器)提供了優雅且可靠的解決方案。本文從常見踩坑出發,層層遞進到自定義上下文管理器,並展示 threading.Lock、open() 等標準庫實戰模式。

問題起點:檔案關閉的坑

# ❌ 錯誤:f 在 try 區塊內定義,finally 看不見
def read_file():
    try:
        f = open('yui', 'r')
        print(''.join(f.readlines()))
    except:
        print('error')
    finally:
        f.close()  # NameError: f not defined

# ❌ 錯誤:open 失敗拋異常,外層 try 捕獲不到
def read_file():
    f = open('azusa', 'r')
    try:
        print(''.join(f.readlines()))
    except:
        print('error')
    finally:
        f.close()

# ❌ 麻煩:雙層 try,重複錯誤處理
def read_file():
    try:
        f = open('sawako', 'r')
        try:
            print(''.join(f.readlines()))
        except:
            print('error')
        finally:
            f.close()
    except:
        print('error')

正解:with 陳述式


def readFile():
    try:
        with open('mio', 'r') as f:
            print(''.join(f.readlines()))
    except:
        print('error occurs while reading file')

優點:open 失敗直接進 except;正常或異常退出 with 區塊時,f.__exit__() 自動關閉檔案。

原理:上下文管理器協定

任何實作 __enter__、__exit__ 的物件皆可用於 with:

  • __enter__():進入區塊時呼叫,回傳值綁定給 as 後的變數。
  • __exit__(exc_type, exc_val, exc_tb):離開區塊時呼叫(含異常)。回傳 True 吞掉異常,False/None 繼續拋出。

自定義範例


class Test:
    def __init__(self):
        print('init')

    def __enter__(self):
        print('enter')
        return self

    def __exit__(self, exc_type, exc_val, tb):
        print('exc_type:', exc_type)
        print('exc_val:', exc_val)
        import traceback
        print(''.join(traceback.format_tb(tb)))
        print('exit')
        return True  # 吞掉異常

with Test() as t:
    raise ValueError('kon!')

init
enter
exc_type: 
exc_val: kon!
File "test.py", line 17, in 
  raise ValueError('kon!')
exit

實戰經典:threading.Lock 與死鎖避免


# ❌ 危險:heappop 拋 IndexError 導致 lock 永不釋放 → 死鎖
lock = threading.Lock()
lock.acquire()
elem = heapq.heappop(heap)
lock.release()

# ✅ try/finally 可行但冗長
lock.acquire()
try:
    elem = heapq.heappop(heap)
finally:
    lock.release()

# ✅✅ with 一行解決,任何方式離開都釋放鎖
with lock:
    elem = heapq.heappop(heap)

標準庫內建上下文管理器速查

物件用途__exit__ 行為
open(...)檔案讀寫自動關閉檔案
threading.Lock()執行緒同步釋放鎖
socket.create_connection()網路連線關閉 socket
decimal.localcontext()暫時修改精度恢復原精度
contextlib.redirect_stdout()重導向標準輸出恢復 stdout

進階:contextlib 快速建立管理器


from contextlib import contextmanager

@contextmanager
def timer(label):
    start = time.perf_counter()
    try:
        yield
    finally:
        print(f"{label}: {time.perf_counter() - start:.3f}s")

with timer("資料庫查詢"):
    db.query(...)

掌握 with 與上下文管理器,能讓資源管理代碼從「易漏、難讀、難維護」蛻變為「安全、清晰、可組合」,是 Python 工程化的標誌性技能之一。

copyright © 萬盛學電腦網 all rights reserved