With語句是什麼?
有一些任務,可能事先需要設定,事後做清理工作。對於這種場景,Python的with語句提供了一種非常方便的處理方式。一個很好的例子是檔案處理,你需要獲取一個檔案控制代碼,從檔案中讀取資料,然後關閉檔案控制代碼。
如果不用with語句,程式碼如下:
1 2 3 |
file =
open
(
"/tmp/foo.txt"
)
data
=
file
.read()
file
.close()
|
這裡有兩個問題。一是可能忘記關閉檔案控制代碼;二是檔案讀取資料發生異常,沒有進行任何處理。下面是處理異常的加強版本:
1 2 3 4 5 |
file
=
open
(
"/tmp/foo.txt"
)
try :
data
=
file
.read()
finally
:
file
.close()
|
雖然這段程式碼執行良好,但是太冗長了。這時候就是with一展身手的時候了。除了有更優雅的語法,with還可以很好的處理上下文環境產生的異常。下面是with版本的程式碼:
?1 2 |
with
open
(
"/tmp/foo.txt"
) as
file
:
data
=
file
.read()
|
with如何工作?
這看起來充滿魔法,但不僅僅是魔法,Python對with的處理還很聰明。基本思想是with所求值的物件必須有一個__enter__()方法,一個__exit__()方法。
緊跟with後面的語句被求值後,返回物件的__enter__()方法被呼叫,這個方法的返回值將被賦值給as後面的變數。當with後面的程式碼塊全部被執行完之後,將呼叫前面返回物件的__exit__()方法。
下面例子可以具體說明with如何工作:
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#!/usr/bin/env python
# with_example01.py
class
Sample:
def
__enter__(
self
):
print
"In __enter__()"
return
"Foo"
def
__exit__(
self
,
type
, value, trace):
print
"In __exit__()"
def
get_sample():
return
Sample()
with get_sample() as sample:
print
"sample:"
, sample
|
執行程式碼,輸出如下
In __enter__()
sample: Foo
In __exit__()
正如你看到的,
1. __enter__()方法被執行
2. __enter__()方法返回的值 - 這個例子中是"Foo",賦值給變數'sample'
3. 執行程式碼塊,列印變數"sample"的值為 "Foo"
4. __exit__()方法被呼叫
with真正強大之處是它可以處理異常。可能你已經注意到Sample類的__exit__方法有三個引數- val, type 和 trace。 這些引數在異常處理中相當有用。我們來改一下程式碼,看看具體如何工作的。
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#!/usr/bin/env python
# with_example02.py
class
Sample:
def
__enter__(
self
):
return
self
def
__exit__(
self
,
type
, value, trace):
print
"type:"
,
type
print
"value:"
, value
print
"trace:"
, trace
def
do_something(
self
):
bar
=
1
/
0
return
bar
+
10
with Sample() as sample:
sample.do_something()
|
這個例子中,with後面的get_sample()變成了Sample()。這沒有任何關係,只要緊跟with後面的語句所返回的物件有__enter__()和__exit__()方法即可。此例中,Sample()的__enter__()方法返回新建立的Sample物件,並賦值給變數sample。
程式碼執行後:
bash-3.2$ ./with_example02.py
type: <type 'exceptions.ZeroDivisionError'>
value: integer division or modulo by zero
trace: <traceback object at 0x1004a8128>
Traceback (most recent call last):
File "./with_example02.py", line 19, in <module>
sample.do_something()
File "./with_example02.py", line 15, in do_something
bar = 1/0
ZeroDivisionError: integer division or modulo by zero
實際上,在with後面的程式碼塊丟擲任何異常時,__exit__()方法被執行。正如例子所示,異常丟擲時,與之關聯的type,value和stack trace傳給__exit__()方法,因此丟擲的ZeroDivisionError異常被打印出來了。開發庫時,清理資源,關閉檔案等等操作,都可以放在__exit__方法當中。
因此,Python的with語句是提供一個有效的機制,讓程式碼更簡練,同時在異常產生時,清理工作更簡單。
with-as語句
從python2.6開始,with就成為預設關鍵字了。With是一個控制流語句,跟if for while try之類的是一類,with可以用來簡化try-finally程式碼,看起來比try finally更清晰,所以說with用很優雅的方式處理上下文環境產生的異常。with關鍵字的用法如下:
?1 2 |
with expression as variable:
with block
|
該程式碼快的執行過程是:
1.先執行expression,然後執行該表示式返回的物件例項的__enter__函式,然後將該函式的返回值賦給as後面的變數。(注意,是將__enter__函式的返回值賦給變數)
2.然後執行with block程式碼塊,不論成功,錯誤,異常,在with block執行結束後,會執行第一步中的例項的__exit__函式
with-as語句使用舉例
(1)開啟檔案的例子
with-as語句最常見的一個用法是開啟檔案的操作,如下:
?1 2 |
with
open
(
"decorator.py"
) as
file
:
print
file
.readlines()
|
(2)自定義
with語句後面的物件必須要有__enter__和__exit__方法,如下是一個自定義的例子:
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class
WithTest():
def
__init__(
self
,name):
self
.name
=
name
pass
def
__enter__(
self
):
print
"This is enter function"
return
self
def
__exit__(
self
,e_t,e_v,t_b):
print
"Now, you are exit"
def
playNow(
self
):
print
"Now, I am playing"
print
"**********"
with WithTest(
"coolboy"
) as test:
print
type
(test)
test.playNow()
print
test.name
print
"**********"
|
上述程式碼執行的結果如下:
**********
This is enter function
<type 'instance'>
Now, I am playing
coolboy
Now, you are exit
**********
分析以上程式碼: 一二行,執行open函式,該函式返回一個檔案物件的例項,然後執行了該例項的__enter__函式,該函式返回此例項本身,最後賦值給file變數。從456句可以印證。
自定義的類WithTest,過載了__enter__和__exit__函式,就可以實現with這樣的語法了,注意在__enter__函式中,返回了self,在__exit__函式中,可以通過__exit__的返回值來指示with-block部分發生的異常是否需要reraise,如果返回false,則會reraise with block異常,如果返回ture,則就像什麼也沒發生。
上下文管理器contextlib模組對with-as的支援
contextlib 模組提供了3個物件:裝飾器 contextmanager、函式 nested 和上下文管理器 closing。使用這些物件,可以對已有的生成器函式或者物件進行包裝,加入對上下文管理協議的支援,避免了專門編寫上下文管理器來支援 with 語句。
以contextlib的closing來說,closing幫助實現了__enter__和__exit__方法,使用者不需要自己再實現這兩個方法,但是被closing分裝的物件必須提供close方法。contextlib.closing類的實現程式碼如下:
?1 2 3 4 5 6 7 8 |
class
closing(
object
):
# help doc here
def
__init__(
self
, thing):
self
.thing
=
thing
def
__enter__(
self
):
return
self
.thing
def
__exit__(
self
,
*
exc_info):
self
.thing.close()
|
下面是一個使用contextlib.closing的例子:
?1 2 3 4 |
import
contextlib
request_url
=
(
'http://www.sina.com.cn/'
)
with contextlib.closing(urlopen(request_url)) as response:
return
response.read().decode(
'utf-8'
)
|