萬盛學電腦網

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

Python with 陳述式:優雅管理資源的上下文管理器協議

with 陳述式取代傳統 try...finally,透過上下文管理器協議(__enter__/__exit__)確保資源正確釋放,即使發生例外也能自動清理。

基本語法

with EXPRESSION [as VARIABLE]:
    WITH-BLOCK

EXPRESSION 必須返回一個擁有 __enter__() 與 __exit__() 方法的物件。

經典檔案處理對比

傳統寫法

file = open('/tmp/foo.txt')
try:
    data = file.read()
finally:
    file.close()

with 寫法(推薦)

with open('/tmp/foo.txt') as file:
    data = file.read()  # 區塊結束自動呼叫 file.close()

自訂上下文管理器

class Sample:
    def __enter__(self):
        print("In __enter__()")
        return "Foo"  # 此返回值賦值給 as 後的變數

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("In __exit__()")
        # 若返回 True 可抑制例外

def get_sample():
    return Sample()

with get_sample() as sample:
    print("sample:", sample)

# 輸出:
# In __enter__()
# sample: Foo
# In __exit__()

例外處理進階

__exit__(exc_type, exc_val, exc_tb) 三個參數分別為例外類型、例外實例、回溯物件。若區塊內拋出例外,這三個參數會帶有對應資訊;若正常結束則全為 None。返回 True 可吞噬例外,False 或 None 則繼續拋出。

內建支援 with 的物件

  • 檔案物件(open())
  • threading.Lock、RLock、Condition、Semaphore
  • decimal.localcontext
  • contextlib.closing、contextlib.suppress 等工具函數
copyright © 萬盛學電腦網 all rights reserved