Python 的 with 語句詳解
一、簡介
with是從Python 2.5 引入的一個新的語法,更準確的說,是一種上下文的管理協(xié)議,用于簡化try…except…finally的處理流程。with通過__enter__方法初始化,然后在__exit__中做善后以及處理異常。對于一些需要預先設置,事后要清理的一些任務,with提供了一種非常方便的表達。
with的基本語法如下,EXPR是一個任意表達式,VAR是一個單一的變量(可以是tuple),”as VAR”是可選的。
with EXPR as VAR:
BLOCK
根據PEP 343的解釋,with…as…會被翻譯成以下語句:
mgr = (EXPR)
exit = type(mgr).__exit__ # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
try:
VAR = value # Only if "as VAR" is present
BLOCK
except:
# The exceptional case is handled here
exc = False
if not exit(mgr, *sys.exc_info()):
raise
# The exception is swallowed if exit() returns true
finally:
# The normal and non-local-goto cases are handled here
if exc:
exit(mgr, None, None, None)
為什么這么復雜呢?注意finally中的代碼,需要BLOCK被執(zhí)行后才會執(zhí)行finally的清理工作,因為當EXPR執(zhí)行時拋出異常,訪問mgr.exit執(zhí)行就會報AttributeError的錯誤。
二、實現方式
根據前面對with的翻譯可以看到,被with求值的對象必須有一個__enter__方法和一個__exit__方法。稍微看一個文件讀取的例子吧,注意在這里我們要解決2個問題:文件讀取異常,讀取完畢后關閉文件句柄。用try…except一般會這樣寫:
f = open('/tmp/tmp.txt')
try:
for line in f.readlines():
print(line)
finally:
f.close()
注意我們這里沒有處理文件打開失敗的IOError,上面的寫法可以正常工作,但是對于每個打開的文件,我們都要手動關閉文件句柄。如果要使用with來實現上述功能,需要需要一個代理類:
class opened(object):
def __init__(self, name):
self.handle = open(name)
def __enter__(self):
return self.handle
def __exit__(self, type, value, trackback):
self.handle.close()
with opened('/tmp/a.txt') as f:
for line in f.readlines():
print(line)
注意我們定了一個名字叫opened的輔助類,并實現了__enter__和__exit__方法,__enter__方法沒有參數,__exit__方法的3個參數,分別代表異常的類型、值、以及堆棧信息,如果沒有異常,3個入參的值都為None。
如果你不喜歡定義class,還可以用Python標準庫提供的contextlib來實現:
from contextlib import contextmanager
@contextmanager
def opened(name):
f = open(name)
try:
yield f
finally:
f.close()
with opened('/tmp/a.txt') as f:
for line in f.readlines():
print(line)
使用contextmanager的函數,yield只能返回一個參數,而yield后面是處理清理工作的代碼。在我們讀取文件的例子中,就是關閉文件句柄。這里原理上和我們之前實現的類opened是相同的,有興趣的可以參考一下contextmanager的源代碼。
三、應用場景
廢話了這么多,那么到底那些場景下該使用with,有沒有一些優(yōu)秀的例子?當然啦,不然這篇文章意義何在。以下摘自PEP 343。
一個確保代碼執(zhí)行前加鎖,執(zhí)行后釋放鎖的模板:
@contextmanager
def locked(lock):
lock.acquire()
try:
yield
finally:
lock.release()
with locked(myLock):
# Code here executes with myLock held. The lock is
# guaranteed to be released when the block is left (even
# if via return or by an uncaught exception).
數據庫事務的提交和回滾:
@contextmanager
def transaction(db):
db.begin()
try:
yield None
except:
db.rollback()
raise
else:
db.commit()
重定向stdout:
@contextmanager
def stdout_redirected(new_stdout):
save_stdout = sys.stdout
sys.stdout = new_stdout
try:
yield None
finally:
sys.stdout = save_stdout
with opened(filename, "w") as f:
with stdout_redirected(f):
print "Hello world"
注意上面的例子不是線程安全的,再多線程環(huán)境中要小心使用。
四、總結
with是對try…expect…finally語法的一種簡化,并且提供了對于異常非常好的處理方式。在Python有2種方式來實現with語法:class-based和decorator-based,2種方式在原理上是等價的,可以根據具體場景自己選擇。
with最初起源于一種block…as…的語法,但是這種語法被很多人所唾棄,最后誕生了with,關于這段歷史依然可以去參考PEP-343和PEP-340
相關文章
Python requests及aiohttp速度對比代碼實例
這篇文章主要介紹了Python requests及aiohttp速度對比代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-07-07分析PyTorch?Dataloader報錯ValueError:num_samples的另一種可能原因
這篇文章主要介紹了分析PyTorch?Dataloader報錯ValueError:num_samples的另一種可能原因,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02