with EXPR as VAR: BLOCK
**上下文管理器是內部實現了__enter__和__exit__方法的對象**python
class Foo: def __init__(self): print("實例化一個對象") def __enter__(self): print("進入") return self def __exit__(self, exc_type, exc_val, exc_tb): print("退出") return True def func(self): print("被執行的方法") with Foo() as f: f.func() >>>實例化一個對象 >>>進入 >>>被執行的方法 >>>退出
__enter__
方法說明數據庫
上下文管理器的__enter__方法是能夠帶返回值的,默認返回None,這個返回值經過with...as...中的 as 賦給它後面的那個變量,因此 with EXPR as VAR 就是將EXPR對象__enter__方法的返回值賦給 VAR,VAR能夠是單個變量,或者由「()」括起來的元組(不能是僅僅由「,」分隔的變量列表,必須加「()」)。 with...as...並不是固定組合,單獨使用with...也是能夠的,上下文管理器的__enter__方法仍是正常執行,只是這個返回值並無賦給一個變量,with下面的代碼塊也不能使用這個返回值。
__exit__
方法說明函數
上下文管理器的__exit__方法接收3個參數exc_type、exc_val、exc_tb,若是代碼塊BLOCK發生了異常e並退出,這3個參數分別爲type(e)、str(e)、e.__traceback__,不然都爲None。 一樣__exit__方法也是能夠帶返回值的,這個返回值應該是一個布爾類型True或False,默認爲None(即False)。若是爲False,異常會被拋出,用戶須要進行異常處理。若是爲True,則表示忽略該異常。
處理異常,一般都是使用 try...execept..
來捕獲處理的。這樣作一個很差的地方是,在代碼的主邏輯裏,會有大量的異常處理代理,這會很大的影響咱們的可讀性。代理
好一點的作法呢,可使用 with
將異常的處理隱藏起來。code
仍然是以上面的代碼爲例,咱們將1/0
這個必定會拋出異常的代碼
寫在 func
裏對象
__exit__
函數的三個參數ci
class Foo: def __init__(self): print("實例化一個對象") def __enter__(self): print("進入") return self def __exit__(self, exc_type, exc_val, exc_tb): import traceback if exc_val: print("異常類型:",exc_type) print("異常值:",exc_val) traceback.print_tb(exc_tb,-1)#打印最開始的錯誤信息,可設置錯誤棧數以及寫入文件 print("退出") return True def func(self): print(1 / 0) print("被執行的方法") with Foo() as f: f.func() --------------------------------------------- 實例化一個對象 進入 File "F:/PyProgram/test98/test1.py", line 62, in func print(1 / 0) 異常類型: <class 'ZeroDivisionError'> 異常值: division by zero 退出
在咱們平常使用場景中,常常會操做一些資源,好比文件對象、數據庫鏈接、Socket鏈接等,資源操做完了以後,無論操做的成功與否,最重要的事情就是關閉該資源,不然資源打開太多而沒有關閉,程序會報錯 。資源
file decimal.Context thread.LockType threading.Lock threading.RLock threading.Condition threading.Semaphore threading.BoundedSemaphore
Python還提供了一個contextmanager裝飾器,容許用戶將一個生成器定義爲上下文管理器,該裝飾器將生成器中的代碼經過yield語句分紅兩部分,yield以前的代碼爲__enter__
方法,yield以後的代碼爲__exit__
方法,yield的返回值即__enter__
方法的返回值,用於賦給as後的變量。it
import contextlib @contextlib.contextmanager def open_func(file_name): # __enter__方法 print('open file:', file_name, 'in __enter__') file_handler = open(file_name, 'r') # 【重點】:yield yield file_handler # __exit__方法 print('close file:', file_name, 'in __exit__') file_handler.close() return with open_func('userinfo.txt') as file_in: for line in file_in: print(line)
import contextlib import traceback import sys @contextlib.contextmanager def open_func(file_name): # __enter__方法 print('open file:', file_name, 'in __enter__') file_handler = open(file_name, 'r') try: yield file_handler except Exception as exc: exc_type, exc_val, exc_tb = sys.exc_info() print("異常類型:", exc_type) print("異常值:", exc_val) traceback.print_tb(exc_tb, -1) print('the exception was thrown') finally: print('close file:', file_name, 'in __exit__') file_handler.close() return with open_func('userinfo.txt') as file_in: for line in file_in: print(1/0) print(line)