Python是一種被廣泛使用的強大語言,讓我們深入這種語言,并且學習一些控制語句的技巧,標準庫的竅門和一些常見的陷阱。
Python(和它的各種庫)非常龐大。它被用于系統自動化、web應用、大數據、數據分析及安全軟件。這篇文件旨在展示一些知之甚少的技巧,這些技巧將帶領你走上一條開發速度更快、調試更容易并且充滿趣味的道路。
學習Python和學習所有其他語言一樣,真正有用的資源不是各個語言繁瑣的超大官方文檔,而是使用常用語法、庫和Python社區共享知識的能力。
探索標準數據類型
謙遜的enumerate
遍歷在Python中非常簡單,使用“for foo in bar:”就可以。
1
2
3
4
5
6
7
|
drinks = [ "coffee" , "tea" , "milk" , "water" ] for drink in drinks: print ( "thirsty for" , drink) #thirsty for coffee #thirsty for tea #thirsty for milk #thirsty for water |
但是同時使用元素的序號和元素本身也是常見的需求。我們經常看到一些程序員使用len()和range()來通過下標迭代列表,但是有一種更簡單的方式。
1
2
3
4
5
6
7
|
drinks = [ "coffee" , "tea" , "milk" , "water" ] for index, drink in enumerate (drinks): print ( "Item {} is {}" . format (index, drink)) #Item 0 is coffee #Item 1 is tea #Item 2 is milk #Item 3 is water |
enumerate 函數可以同時遍歷元素及其序號。
Set類型
許多概念都可以歸結到對集合(set)的操作。例如:確認一個列表沒有重復的元素;查看兩個列表共同的元素等等。Python提供了set數據類型以使類似這樣的操作更快捷更具可讀性。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
# deduplicate a list *fast* print ( set ([ "ham" , "eggs" , "bacon" , "ham" ])) # {'bacon', 'eggs', 'ham'} # compare lists to find differences/similarities # {} without "key":"value" pairs makes a set menu = { "pancakes" , "ham" , "eggs" , "bacon" } new_menu = { "coffee" , "ham" , "eggs" , "bacon" , "bagels" } new_items = new_menu.difference(menu) print ( "Try our new" , ", " .join(new_items)) # Try our new bagels, coffee discontinued_items = menu.difference(new_menu) print ( "Sorry, we no longer have" , ", " .join(discontinued_items)) # Sorry, we no longer have pancakes old_items = new_menu.intersection(menu) print ( "Or get the same old" , ", " .join(old_items)) # Or get the same old eggs, bacon, ham full_menu = new_menu.union(menu) print ( "At one time or another, we've served:" , ", " .join(full_menu)) # At one time or another, we've served: coffee, ham, pancakes, bagels, bacon, eggs |
intersection 函數比較列表中所有元素,返回兩個集合的交集。在我們的例子中,早餐的主食為bacon、eggs和ham。
collections.namedtuple
如果你不想給一個類添加方法,但又想使用foo.prop的調用方式,那么你需要的就是namedtuple。你提前定義好類屬性,然后就可以實例化一個輕量級的類,這樣的方式會比完整的對象占用更少的內存。
1
2
3
4
5
|
LightObject = namedtuple( 'LightObject' , [ 'shortname' , 'otherprop' ]) m = LightObject() m.shortname = 'athing' > Traceback (most recent call last): > AttributeError: can't set attribute |
用這種方式你無法設置namedtuple的屬性,正如你不能修改元組(tuple)中元素的值。你需要在實例化namedtuple的時候設置屬性的值。
1
2
3
4
5
|
LightObject = namedtuple( 'LightObject' , [ 'shortname' , 'otherprop' ]) n = LightObject(shortname = 'something' , otherprop = 'something else' ) n.shortname # something collections.defaultdict |
在寫Python應用使用字典時,很多時候有些關鍵字一開始并不存在,例如下面的例子。
1
2
3
4
5
6
|
login_times = {} for t in logins: if login_times.get(t.username, None ): login_times[t.username].append(t.datetime) else : login_times[t.username] = [t.datetime] |
使用defaultdict 我們可以跳過檢查關鍵字是否存在的邏輯,對某個未定義key的任意訪問,都會返回一個空列表(或者其他數據類型)。
1
2
3
|
login_times = collections.defaultdict( list ) for t in logins: login_times[t.username].append(t.datetime) |
你甚至可以使用自定義的類,這樣調用的時候實例化一個類。
1
2
3
4
5
6
7
8
9
10
11
12
|
from datetime import datetime class Event( object ): def __init__( self , t = None ): if t is None : self .time = datetime.now() else : self .time = t events = collections.defaultdict(Event) for e in user_events: print (events[e.name].time) |
如果既想具有defaultdict的特性,同時還想用訪問屬性的方式來處理嵌套的key,那么可以了解一下 addict。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
normal_dict = { 'a' : { 'b' : { 'c' : { 'd' : { 'e' : 'really really nested dict' } } } } } from addict import Dict addicted = Dict () addicted.a.b.c.d.e = 'really really nested' print (addicted) # {'a': {'b': {'c': {'d': {'e': 'really really nested'}}}}} |
這段小程序比標準的dict要容易寫的多。那么為什么不用defaultdict呢? 它看起來也夠簡單了。
1
2
3
4
|
from collections import defaultdict default = defaultdict( dict ) default[ 'a' ][ 'b' ][ 'c' ][ 'd' ][ 'e' ] = 'really really nested dict' # fails |
這段代碼看起來沒什么問題,但是它最終拋出了KeyError異常。這是因為default[‘a']是dict,不是defaultdict.讓我們構造一個value是defaulted dictionaries類型的defaultdict,這樣也只能解決兩級嵌套。
如果你只是需要一個默認計數器,你可以使用collection.Counter,這個類提供了許多方便的函數,例如 most_common.
控制流
當學習Python中的控制結構時,通常要認真學習 for, while,if-elif-else, 和 try-except。只要正確使用,這幾個控制結構能夠處理絕大多數的情況。也是基于這個原因,幾乎你所遇到的所有語言都提供類似的控制結構語句。在基本的控制結構以外,Python也額外提供一些不常用的控制結構,這些結構會使你的代碼更具可讀性和可維護性。
Great Exceptations
Exceptions作為一種控制結構,在處理數據庫、sockets、文件或者任何可能失敗的資源時非常常用。使用標準的 try 、except 結構寫數據庫操作時通常是類型這樣的方式。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
try : # get API data data = db.find( id = 'foo' ) # may raise exception # manipulate the data db.add(data) # save it again db.commit() # may raise exception except Exception: # log the failure db.rollback() db.close() |
你能發現這里的問題嗎?這里有兩種可能的異常會觸發相同的except模塊。這意味著查找數據失?。ɑ蛘邽椴樵償祿⑦B接失?。l回退操作。這絕對不是我們想要的,因為在這個時間點上事務并沒有開始。同樣回退也不應該是數據庫連接失敗的正確響應,因此讓我們將不同的情況分開處理。
首先,我們將處理查詢數據。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
try : # get API data data = db.find( id = 'foo' ) # may raise exception except Exception: # log the failure and bail out log.warn( "Could not retrieve FOO" ) return # manipulate the data db.add(data) |
現在數據檢索擁有自己的try-except,這樣當我們沒有取得數據時,我們可以采取任何處理方式。沒有數據我們的代碼不大可能再做有用的事,因此我們將僅僅退出函數。除了退出你也可以構造一個默認對象,重新進行檢索或者結束整個程序。
現在讓我們將commit的代碼也單獨包起來,這樣它也能更優雅的進行錯誤處理。
1
2
3
4
5
6
7
8
9
10
|
try : db.commit() # may raise exception except Exception: log.warn( "Failure committing transaction, rolling back" ) db.rollback() else : log.info( "Saved the new FOO" ) finally : db.close() |
實際上,我們已經增加了兩端代碼。首先,讓我們看看else,當沒有異常發生時會執行這里的代碼。在我們的例子中,這里只是將事務成功的信息寫入日志,但是你可以按照需要進行更多有趣的操作。一種可能的應用是啟動后臺任務或者通知。
很明顯finally 子句在這里的作用是保證db.close() 總是能夠運行?;仡櫼幌拢覀兛梢钥吹剿泻蛿祿鎯ο嚓P的代碼最終都在相同的縮進級別中形成了漂亮的邏輯分組。以后需要進行代碼維護時,將很直觀的看出這幾行代碼都是用于完成 commit操作的。
Context and Control
之前,我們已經看到使用異常來進行處理控制流。通常,基本步驟如下:
- 嘗試獲取資源(文件、網絡連接等)
- 如果失敗,清除留下的所有東西
- 成功獲得資源則進行相應操作
- 寫日志
- 程序結束
考慮到這一點,讓我們再看一下上一章數據庫的例子。我們使用try-except-finally來保證任何我們開始的事務要么提交要么回退。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
try : # attempt to acquire a resource db.commit() except Exception: # If it fails, clean up anything left behind log.warn( "Failure committing transaction, rolling back" ) db.rollback() else : # If it works, perform actions # In this case, we just log success log.info( "Saved the new FOO" ) finally : # Clean up db.close() # Program complete |
我們前面的例子幾乎精確的映射到剛剛提到的步驟。這個邏輯變化的多嗎?并不多。
差不多每次存儲數據,我們都將做相同的步驟。我們可以將這些邏輯寫入一個方法中,或者我們可以使用上下文管理器(context manager)
1
2
3
4
5
6
7
8
9
10
|
db = db_library.connect( "fakesql://" ) # as a function commit_or_rollback(db) # context manager with transaction( "fakesql://" ) as db: # retrieve data here # modify data here |
上下文管理器通過設置代碼段運行時需要的資源(上下文環境)來保護代碼段。在我們的例子中,我們需要處理一個數據庫事務,那么過程將是這樣的:
- 連接數據庫
- 在代碼段的開頭開始操作
- 在代碼段的結尾提交或者回滾
- 在代碼段的結尾清除資源
讓我們建立一個上下文管理器,使用上下文管理器為我們隱藏數據庫的設置工作。contextmanager 的接口非常簡單。上下文管理器的對象需要具有一個__enter__()方法用來設置所需的上下文環境,還需要一個__exit__(exc_type, exc_val, exc_tb) 方法在離開代碼段之后調用。如果沒有異常,那么三個 exc_* 參數將都是None。
此處的__enter__方法非常簡單,我們先從這個函數開始。
1
2
3
4
5
6
|
class DatabaseTransaction( object ): def __init__( self , connection_info): self .conn = db_library.connect(connection_info) def __enter__( self ): return self .conn |
__enter__方法只是返回數據庫連接,在代碼段內我們使用這個數據庫連接來存取數據。數據庫連接實際上是在__init__ 方法中建立的,因此如果數據庫建立連接失敗,那么代碼段將不會執行。
現在讓我們定義事務將如何在 __exit__ 方法中完成。這里面要做的工作就比較多了,因為這里要處理代碼段中所有的異常并且還要完成事務的關閉工作。
1
2
3
4
5
6
7
8
9
10
|
def __exit__( self , exc_type, exc_val, exc_tb): if exc_type is not None : self .conn.rollback() try : self .conn.commit() except Exception: self .conn.rollback() finally : self .conn.close() |
現在我們就可以使用 DatabaseTransaction 類作為我們例子中的上下文管理器了。在類內部, __enter__ 和 __exit__ 方法將開始和設置數據連接并且處理善后工作。
1
2
3
4
5
6
|
# context manager with DatabaseTransaction( "fakesql://" ) as db: # retrieve data here # modify data here |
為了改進我們的(簡單)事務管理器,我們可以添加各種異常處理。即使是現在的樣子,這個事務管理器已經為我們隱藏了許多復雜的處理,這樣你不用每次從數據庫拉取數據時都要擔心與數據庫相關的細節。
生成器
Python 2中引入的生成器(generators)是一種實現迭代的簡單方式,這種方式不會一次產生所有的值。Python中典型的函數行為是開始執行,然后進行一些操作,最后返回結果(或者不返回)。
生成器的行為卻不是這樣的。
1
2
3
4
5
6
7
|
def my_generator(v): yield 'first ' + v yield 'second ' + v yield 'third ' + v print (my_generator( 'thing' )) # <generator object my_generator at 0x....> |
使用 yield 關鍵字代替 return ,這就是生成器的獨特之處。當我們調用 my_generator('thing') 時,我得到的不是函數的結果而是一個生成器對象,這個生成器對象可以在任何我們使用列表或其他可迭代對象的地方使用。
更常見的用法是像下面例子那樣將生成器作為循環的一部分。循環會一直進行,直到生成器停止 yield值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
for value in my_generator( 'thing' ): print value # first thing # second thing # third thing gen = my_generator( 'thing' ) next (gen) # 'first thing' next (gen) # 'second thing' next (gen) # 'third thing' next (gen) # raises StopIteration exception |
生成器實例化之后不做任何事直到被要求產生數值,這時它將一直執行到遇到第一個 yield 并且將這個值返回給調用者,然后生成器保存上下文環境后掛起一直到調用者需要下一個值。
現在我們來寫一個比剛才返回三個硬編碼的值更有用的生成器。經典的生成器例子是一個無窮的斐波納契數列生成器,我們來試一試。數列從1開始,依次返回前兩個數之和。
1
2
3
4
5
6
|
def fib_generator(): a = 0 b = 1 while True : yield a a, b = b, a + b |
函數中的 while True 循環通常情況下應該避免使用,因為這會導致函數無法返回,但是對于生成器卻無所謂,只要保證循環中有 yield 。我們在使用這種生成器的時候要注意添加結束條件,因該生成器可以持續不斷的返回數值。
現在,使用我們的生成器來計算第一個大于10000的斐波納契數列值。
1
2
3
4
5
|
min = 10000 for number in fib_generator(): if number > min : print (number, "is the first fibonacci number over" , min ) break |
這非常簡單,我們可以把數值定的任意大,代碼最終都會產生斐波納契數列中第一個大于X的值。
讓我們看一個更實際的例子。翻頁接口是應對應用限制和避免向移動設備發送大于50兆JSON數據包的一種常見方法。首先,我們定義需要的API,然后我們為它寫一個生成器在我們的代碼中隱藏翻頁邏輯。
我們使用的API來自Scream,這是一個用戶討論他們吃過的或想吃的餐廳的地方。他們的搜索API非常簡單,基本是下面這樣。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
GET http: / / scream - about - food.com / search?q = coffee { "results" : [ { "name" : "Coffee Spot" , "screams" : 99 }, { "name" : "Corner Coffee" , "screams" : 403 }, { "name" : "Coffee Moose" , "screams" : 31 }, {...} ] "more" : true, "_next" : "http://scream-about-food.com/search?q=coffee?p=2" } |
他們將下一頁的鏈接嵌入到API應答中,這樣當需要獲得下一頁時就非常簡單了。我們能夠不考慮頁碼,只是獲取第一頁。為了獲得數據,我們將使用常見的 requests 庫,并且用生成器將其封裝以展示我們的搜索結果。
這個生成器將處理分頁并且限制重試邏輯,它將按照下述邏輯工作:
- 收到要搜索的內容
- 查詢scream-about-food接口
- 如果接口失敗進行重試
- 一次yield一個結果
- 如果有的話,獲取下一頁
- 當沒有更多結果時,退出
非常簡單。我來實現這個生成器,為了簡化代碼我們暫時不考慮重試邏輯。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import requests api_url = "http://scream-about-food.com/search?q={term}" def infinite_search(term): url = api_url. format (term) while True : data = requests.get(url).json() for place in data[ 'results' ]: yield place # end if we've gone through all the results if not data[ 'more' ]: break url = data[ '_next' ] |
當我們創建了生成器,你只需要傳入搜索的內容,然后生成器將會生成請求,如果結果存在則獲取結果。當然這里有些未處理的邊界問題。異常沒有處理,當API失敗或者返回了無法識別的JSON,生成器將拋出異常。
盡管存在這些未處理完善的地方,我們仍然能使用這些代碼獲得我們的餐廳在關鍵字“coffee”搜索結果中的排序。
1
2
3
4
5
6
7
|
# pass a number to start at as the second argument if you don't want # zero-indexing for number, result in enumerate (infinite_search( "coffee" ), 1 ): if result[ 'name' ] = = "The Coffee Stain" : print ( "Our restaurant, The Coffee Stain is number " , number) return print ( "Our restaurant, The Coffee Stain didnt't show up at all! :(" ) |
如果使用Python 3,當你使用標準庫時你也能使用生成器。調用類似 dict.items() 這樣的函數時,不返回列表而是返回生成器。在Python 2中為了獲得這種行為,Python 2中添加了 dict.iteritems() 函數,但是用的比較少。
Python 2 and 3 compatibility
從Python 2 遷移到Python 3對任何代碼庫(或者開發人員)都是一項艱巨的任務,但是寫出兩個版本都能運行的代碼也是可能的。Python 2.7將被支持到2020年,但是許多新的特性將不支持向后兼容。目前,如果你還不能完全放棄Python 2, 那最好使用Python 2.7 和 3+兼容的特性。
對于兩個版本支持特性的全面指引,可以在python.org上看 Porting Python 2 Code 。
讓我們查看一下在打算寫兼容代碼時,你將遇到的最常見的情況,以及如何使用 __future__ 作為變通方案。
print or print()
幾乎每一個從Python 2 切換到Python 3的開發者都會寫出錯誤的print 表達式。幸運的是,你能夠通過導入 print_function 模塊,將print作為一個函數而不是一個關鍵字來寫出可兼容的print.
1
2
3
4
5
6
|
for result in infinite_search( "coffee" ): if result[ 'name' ] = = "The Coffee Stain" : print ( "Our restaurant, The Coffee Stain is number " , result[ 'number' ]) return print ( "Our restaurant, The Coffee Stain didn't show up at all! :(" ) Divided Over Division |
從Python 2 到 Python 3,除法的默認行為也發生了變化。在Python 2中,整數的除法只進行整除,小數部分全部截去。大多數用戶不希望這樣的行為,因此在Python 3中即使是整數之間的除法也執行浮點除。
1
2
3
4
5
6
7
8
9
10
|
print "hello" # Python 2 print ( "hello" ) # Python 3 from __future__ import print_function print ( "hello" ) # Python 2 print ( "hello" ) # Python 3 |
這種行為的改變會導致編寫同時運行在Python 2 和 Python 3上的代碼時,帶來一連串的小bug。我們再一次需要 __future__ 模塊。導入 division 將使代碼在兩個版本中產生相同的運行結果。
1
2
3
4
5
6
7
8
9
|
print ( 1 / 3 ) # Python 2 # 0 print ( 1 / 3 ) # Python 3 # 0.3333333333333333 print ( 1 / / 3 ) # Python 3 # 0 |