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 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 則繼續拋出。
open())threading.Lock、RLock、Condition、Semaphoredecimal.localcontextcontextlib.closing、contextlib.suppress 等工具函數