Python 常用 PEP8 編碼規范
代碼布局
縮進
EXAMPLE:
# (垂直隱式縮進)對準左括號foo = long_function_name(var_one, var_two, var_three, var_four)# (懸掛縮進) 一般情況只需多一層縮進foo = long_function_name( var_one, var_two, var_three, var_four)# (懸掛縮進) 但下面情況, 需再加多一層縮進, 和后續的語句塊區分開來def long_function_name( var_one, var_two, var_three, var_four): print(var_one)# 右括號回退my_list = [ 1, 2, 3, 4, 5, 6,]result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f',)
錯誤示范:
# 不使用垂直對齊時,第一行不能有參數。foo = long_function_name(var_one, var_two, var_three, var_four)# 參數的懸掛縮進和后續代碼塊縮進不能區別。def long_function_name( var_one, var_two, var_three, var_four): print(var_one)# 右括號不回退,不推薦my_list = [ 1, 2, 3, 4, 5, 6, ]result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f', )
最大行寬
EXAMPLE:
# 無括號續行, 利用反斜杠with open('/path/to/some/file/you/want/to/read') as file_1, / open('/path/to/some/file/being/written', 'w') as file_2: file_2.write(file_1.read())# 括號內續行, 盡量在運算符后再續行class Rectangle(Blob): def __init__(self, width, height, color='black', emphasis=None, highlight=0): if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100): raise ValueError("sorry, you lose") if width == 0 and height == 0 and (color == 'red' or emphasis is None): raise ValueError("I don't think so -- values are %s, %s" % (width, height))空行
EXAMPLE:
# 類的方法定義用單個空行分割,兩行空行分割頂層函數和類的定義。class A(object): def method1(): pass def method2(): passdef method3(): pass
模塊導入
EXAMPLE:
# 按模塊首字母排序導入, 依此遞推import activeimport adidasimport create
錯誤示例:
# 一行導入多模塊import sys, os, knife# 不按首字母導入import createimport activeimport beyond
字符串
單引號和雙引號作用是一樣的,但必須保證成對存在,不能夾雜使用. (建議句子使用雙引號, 單詞使用單引號, 但不強制.)
EXAMPLE:
# 單引號和雙引號效果一樣name = 'JmilkFan'name = "Hey Guys!"
表達式和語句中的空格
括號里邊避免空格
EXAMPLE:
spam(ham[1], {eggs: 2})錯誤示例:
spam( ham[ 1 ], { eggs: 2 } )逗號,冒號,分號之前避免空格
EXAMPLE:
if x == 4: print x, y; x, y = y, x
錯誤示例:
if x == 4 : print x , y ; x , y = y , x
函數調用的左括號之前不能有空格
EXAMPLE:
spam(1)dct['key'] = lst[index]
錯誤示例:
spam (1)dct ['key'] = lst [index]
賦值等操作符前后不能因為對齊而添加多個空格
EXAMPLE:
x = 1y = 2long_variable = 3
錯誤示例:
x = 1y = 2long_variable = 3
二元運算符兩邊放置一個空格
EXAMPLE:
a = ba or b# 括號內的操作符不需要空格name = get_name(age, sex=None, city=Beijing)
注釋
注釋塊
注釋塊通常應用在代碼前,并和代碼有同樣的縮進。每行以 ‘# ' 開頭, 而且#后面有單個空格。
EXAMPLE:
# Have to define the param `args(List)`, # otherwise will be capture the CLI option when execute `python manage.py server`.# oslo_config: (args if args is not None else sys.argv[1:])CONF(args=[], default_config_files=[CONFIG_FILE])
單行注釋(應避免無謂的注釋)
EXAMPLE:
x = x + 1 # Compensate for border
文檔字符串
EXAMPLE:
# 多行文檔, 首行首字母大寫,結尾的 """ 應該單獨成行"""Return a foobangOptional plotz says to frobnicate the bizbaz first."""# 單行的文檔, 結尾的 """ 在同一行。"""Return a foobang"""
命名規則
包和模塊名:
包和模塊名應該簡短,全部用小寫字母, 多字母之間可以使用單下劃線連接。
類名:
遵循駝峰命名
class MyClass(object): pass
全局變量名:
全局變量名應盡量只在模塊內部使用, 對可能使用語句 from moduleName import variableName 而被導入的模塊,應采用 __all__ 機制來防止全局變量被別的模塊導入, 或者在全局變量名開頭加一個前置下劃線.
EXAMPLE:
_name = 'name'
函數名
函數名應該為全部小寫的凹駝峰規則。
EXAMPLE:
vcenter_connection = ''
常量名
常量全部使用大寫字母的凹駝峰規則來表示, 通常在模塊頂格定義
EXAMPLE:
MAX_OVERFLOW = ''TOTAL = 1
方法名和實例變量
非公開方法和實例變量開頭使用前置下劃線
有時候可能會為了避免與子類命名沖突,采用兩個前置下劃線
需要注意的是: 若 class Foo 的屬性名為 __a, 該屬性是不能以 Foo.__a 的方式訪問的(執著的用戶還是可以通過Foo._Foo__a 來訪問), 所以通常雙前置下劃線僅被用來避免與基類的屬性發生命名沖突。
編程建議
None 的比較用 is 或 is not,而不要用 ==
用 is not 代替 not … is, 前者的可讀性更好
EXAMPLE:
# Yesif foo is not None# Noif not foo is None
使用函數定義關鍵字 def 代替 lambda 賦值給標識符, 這樣更適合于回調和字符串表示
# Yesdef f(x): return 2*x# Nof = lambda x: 2*x
異常類應該繼承自Exception,而不是 BaseException
Python 2 中用raise ValueError('message') 代替 raise ValueError, 'message'
(考慮兼容python3和續行的方便性)
捕獲異常時盡量指明具體異常, 盡量不用 except Exception, 應該捕獲 出了什么問題,而不是 問題發生
EXAMPLE:
# Yes (捕獲具體異常)try: import platform_specific_moduleexcept ImportError: platform_specific_module = None# No (不要全局捕獲)try: import platform_specific_moduleexcept: platform_specific_module = None
try/except 子句中的代碼要盡可能的少, 以免屏蔽掉其他的錯誤
EXAMPLE:
# Yestry: value = collection[key]except KeyError: return key_not_found(key)else: return handle_value(value)# Notry: return handle_value(collection[key])except KeyError: # 可能會捕捉到 handle_value()中的 KeyError, 而不是 collection 的 return key_not_found(key)
函數或者方法在沒有返回值時要明確返回 None
# Yesdef foo(): return None# Nodef foo(): return
使用字符串方法而不是 string 模塊
python 2.0 以后字符串方法總是更快,而且與 Unicode 字符串使用了相同的 API
使用使用 .startswith() 和 .endswith() 代替字符串切片來檢查前綴和后綴
startswith() 和 endswith 更簡潔,利于減少錯誤
EXAMPLE:
# Yesif foo.startswith('bar'):# Noif foo[:3] == 'bar':使用 isinstance() 代替對象類型的比較
EXAMPLE:
# Yesif isinstance(obj, int):# Noif type(obj) is type(1):
空序列類型對象的 bool 為 False:
# Yesif not seq: passif seq: pass# Noif len(seq): passif not len(seq): pass
不要用 == 進行 bool 比較
# Yesif greeting: pass# Noif greeting == True passif greeting is True: # Worse pass
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答
圖片精選