PEP 8 是python代碼規範說明,裏面規定了一些推薦的python代碼的格式與用法。筆者將在本文中作一些總結,不是爲了純粹的翻譯PEP 8,而是根據我的習慣與喜愛進行的一個整理。若有謬誤,歡迎指出。python
PEP 8 官方文檔:這裏api
永遠不要爲了和已有的文檔保持一致而特地作出不天然的改變,不然,這隻會限制你的思惟,下降你的效率。Guido在這裏寫下的這些規範是處於代碼的可讀性考慮的,可是若是有的時候這些規範也不必定適用,例如:app
若是使用了這些規範會下降可讀性;ide
若是代碼寫於規範面世之前;函數
若是代碼使用到了老版本的依賴庫,然而這些老版本的依賴庫且兼容新的規範;ui
若是已有代碼使用了另外的一種風格;this
多參數狀況下適當縮進spa
# function def long_function_name( # no argument on the first line var_one, var_two, # more indentation to distinguish this from the rest var_three, var_four): print(var_one) # list my_list = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, # add a comma here to be consistent with the preceding lines ] # long if -statement if (this_is_one_thing and that_is_another_thing) # more indentation to distinguish this do_something()
使用4個空格鍵<space>替代製表鍵<tab>翻譯
每行字符數控制在79個之內,必要的時候可以使用\
rest
with open('/path/to/the/file/to/read') as file_1, \ open('/path/to/the/file/to/read') as file_2: file_2.write(file_1.read())
多行分別import依賴庫,且須放在全局變量和常量以前
import os import sys import other_standard_libraries import related_third_parties ipmort local applications
python不區分雙引號"
和單引號'
,選一個適合你本身的風格,而後堅持下去
空白符的規則很繁瑣,基本上和英文書寫的規範一致,下面列舉了部分狀況
ham[1:9], ham[1:9:3], ham[1::3], ham[1:9:] ham[lower+offset : upper+offset] # equal amounts on either side of the operator
在分配默認值或者鍵值對賦值的時候,等號=
周圍不要用空格
def complex(real, imag=0.0): return magic(r=real, i=img)
關於註釋,不要添加與代碼邏輯相違背的註釋,也不要添加顯而易見的註釋。記住一點,註釋是爲了加強可讀性。
關於命名,不一樣的對象會有不一樣的規範:
包:小寫,能夠使用可是不推薦使用下劃線_
。一些利用C/C++編寫的包的名字能夠如下劃線開頭;
類:CapWords命名規範,例如CapitalizeWords
, HTTPServerError
異常:其本質是一個類,因此沿用上面的規範,另外須要以Error_
開頭
函數:小寫,而且用下劃線隔開
方法與變量:沿用函數的命名規範,另外非公有變量須要以_
開頭
與None
做比較的使用,不要使用==
,使用is
或者is not
字符串的合併操做不要使用a += b
或者a = a + b
,使用''.join()
從Excepetion
而不是BaseException
庫中繼承異常
拋出異常的時候,請使用raise ValueError('message')
在捕捉異常語句中,請儘量指明捕捉的異常類別。若是須要捕捉全部擾亂程序的異常,能夠使用
try: some_magic() except Exception as exc: print(str(exc)) raise some_error else: everything_is_good() finally: clean_up()
對於不一樣的輸入,函數的返回值類型應該保持一致
def foo(x): if x >= 0: return math.sqrt(x) else: return None # should also be a value or None
字符串操做中,儘量使用字符串類的方法
''.startswith() ''.endswith()
判斷對象的類別,儘可能使用isinstance()
歡迎討論,歡迎指出問題
Weiming
25 May 2016