Python 常用 PEP8 編碼規(guī)范詳解
Python 常用 PEP8 編碼規(guī)范
代碼布局
縮進(jìn)
- 每級縮進(jìn)用4個空格。
- 括號中使用垂直隱式縮進(jìn)或使用懸掛縮進(jìn)。
EXAMPLE:
# (垂直隱式縮進(jìn))對準(zhǔn)左括號 foo = long_function_name(var_one, var_two, var_three, var_four) # (懸掛縮進(jìn)) 一般情況只需多一層縮進(jìn) foo = long_function_name( var_one, var_two, var_three, var_four) # (懸掛縮進(jìn)) 但下面情況, 需再加多一層縮進(jìn), 和后續(xù)的語句塊區(qū)分開來 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', )
錯誤示范:
# 不使用垂直對齊時,第一行不能有參數(shù)。 foo = long_function_name(var_one, var_two, var_three, var_four) # 參數(shù)的懸掛縮進(jìn)和后續(xù)代碼塊縮進(jìn)不能區(qū)別。 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', )
最大行寬
- 每行最大行寬不超過 79 個字符
- 一般續(xù)行可使用反斜杠
- 括號內(nèi)續(xù)行不需要使用反斜杠
EXAMPLE:
# 無括號續(xù)行, 利用反斜杠 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()) # 括號內(nèi)續(xù)行, 盡量在運算符后再續(xù)行 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))
空行
- 兩行空行用于分割頂層函數(shù)和類的定義
- 單個空行用于分割類定義中的方法
EXAMPLE:
# 類的方法定義用單個空行分割,兩行空行分割頂層函數(shù)和類的定義。 class A(object): def method1(): pass def method2(): pass def method3(): pass
模塊導(dǎo)入
- 導(dǎo)入的每個模塊應(yīng)該單獨成行
- 導(dǎo)入順序如下: (各模塊類型導(dǎo)入之間要有空行分割,各組里面的模塊的順序按模塊首字母自上而下升序排列)
- 標(biāo)準(zhǔn)庫
- 相關(guān)的第三方庫
- 本地庫
EXAMPLE:
# 按模塊首字母排序?qū)? 依此遞推 import active import adidas import create
錯誤示例:
# 一行導(dǎo)入多模塊 import sys, os, knife # 不按首字母導(dǎo)入 import create import active import beyond
字符串
單引號和雙引號作用是一樣的,但必須保證成對存在,不能夾雜使用. (建議句子使用雙引號, 單詞使用單引號, 但不強(qiáng)制.)
EXAMPLE:
# 單引號和雙引號效果一樣 name = 'JmilkFan' name = "Hey Guys!"
表達(dá)式和語句中的空格
括號里邊避免空格
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
函數(shù)調(diào)用的左括號之前不能有空格
EXAMPLE:
spam(1) dct['key'] = lst[index]
錯誤示例:
spam (1) dct ['key'] = lst [index]
賦值等操作符前后不能因為對齊而添加多個空格
EXAMPLE:
x = 1 y = 2 long_variable = 3
錯誤示例:
x = 1 y = 2 long_variable = 3
二元運算符兩邊放置一個空格
- 涉及 = 的復(fù)合操作符 ( += , -=等)
- 比較操作符 ( == , < , > , != , <> , <= , >= , in , not in , is , is not )
- 邏輯操作符( and , or , not )
EXAMPLE:
a = b a or b # 括號內(nèi)的操作符不需要空格 name = get_name(age, sex=None, city=Beijing)
注釋
注釋塊
注釋塊通常應(yīng)用在代碼前,并和代碼有同樣的縮進(jìn)。每行以 ‘# ' 開頭, 而且#后面有單個空格。
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])
單行注釋(應(yīng)避免無謂的注釋)
EXAMPLE:
x = x + 1 # Compensate for border
文檔字符串
EXAMPLE:
# 多行文檔, 首行首字母大寫,結(jié)尾的 """ 應(yīng)該單獨成行 """Return a foobang Optional plotz says to frobnicate the bizbaz first. """ # 單行的文檔, 結(jié)尾的 """ 在同一行。 """Return a foobang"""
命名規(guī)則
包和模塊名:
包和模塊名應(yīng)該簡短,全部用小寫字母, 多字母之間可以使用單下劃線連接。
類名:
遵循駝峰命名
class MyClass(object): pass
全局變量名:
全局變量名應(yīng)盡量只在模塊內(nèi)部使用, 對可能使用語句 from moduleName import variableName 而被導(dǎo)入的模塊,應(yīng)采用 __all__ 機(jī)制來防止全局變量被別的模塊導(dǎo)入, 或者在全局變量名開頭加一個前置下劃線.
EXAMPLE:
_name = 'name'
函數(shù)名
函數(shù)名應(yīng)該為全部小寫的凹駝峰規(guī)則。
EXAMPLE:
vcenter_connection = ''
常量名
常量全部使用大寫字母的凹駝峰規(guī)則來表示, 通常在模塊頂格定義
EXAMPLE:
MAX_OVERFLOW = '' TOTAL = 1
方法名和實例變量
非公開方法和實例變量開頭使用前置下劃線
有時候可能會為了避免與子類命名沖突,采用兩個前置下劃線
需要注意的是: 若 class Foo 的屬性名為 __a, 該屬性是不能以 Foo.__a 的方式訪問的(執(zhí)著的用戶還是可以通過Foo._Foo__a 來訪問), 所以通常雙前置下劃線僅被用來避免與基類的屬性發(fā)生命名沖突。
編程建議
None 的比較用 is 或 is not,而不要用 ==
用 is not 代替 not … is, 前者的可讀性更好
EXAMPLE:
# Yes if foo is not None # No if not foo is None
使用函數(shù)定義關(guān)鍵字 def 代替 lambda 賦值給標(biāo)識符, 這樣更適合于回調(diào)和字符串表示
# Yes def f(x): return 2*x # No f = lambda x: 2*x
異常類應(yīng)該繼承自Exception,而不是 BaseException
Python 2 中用raise ValueError('message') 代替 raise ValueError, 'message'
(考慮兼容python3和續(xù)行的方便性)
捕獲異常時盡量指明具體異常, 盡量不用 except Exception, 應(yīng)該捕獲 出了什么問題,而不是 問題發(fā)生
EXAMPLE:
# Yes (捕獲具體異常) try: import platform_specific_module except ImportError: platform_specific_module = None # No (不要全局捕獲) try: import platform_specific_module except: platform_specific_module = None
try/except 子句中的代碼要盡可能的少, 以免屏蔽掉其他的錯誤
EXAMPLE:
# Yes try: value = collection[key] except KeyError: return key_not_found(key) else: return handle_value(value) # No try: return handle_value(collection[key]) except KeyError: # 可能會捕捉到 handle_value()中的 KeyError, 而不是 collection 的 return key_not_found(key)
函數(shù)或者方法在沒有返回值時要明確返回 None
# Yes def foo(): return None # No def foo(): return
使用字符串方法而不是 string 模塊
python 2.0 以后字符串方法總是更快,而且與 Unicode 字符串使用了相同的 API
使用使用 .startswith() 和 .endswith() 代替字符串切片來檢查前綴和后綴
startswith() 和 endswith 更簡潔,利于減少錯誤
EXAMPLE:
# Yes if foo.startswith('bar'): # No if foo[:3] == 'bar':
使用 isinstance() 代替對象類型的比較
EXAMPLE:
# Yes if isinstance(obj, int): # No if type(obj) is type(1):
空序列類型對象的 bool 為 False:
# Yes if not seq: pass if seq: pass # No if len(seq): pass if not len(seq): pass
不要用 == 進(jìn)行 bool 比較
# Yes if greeting: pass # No if greeting == True pass if greeting is True: # Worse pass
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
LyScript實現(xiàn)Hook隱藏調(diào)試器的方法詳解
LyScript?插件集成的內(nèi)置API函數(shù)可靈活的實現(xiàn)繞過各類反調(diào)試保護(hù)機(jī)制。本文將運用LyScript實現(xiàn)繞過大多數(shù)通用調(diào)試機(jī)制,實現(xiàn)隱藏調(diào)試器的目的,需要的可以參考一下2022-09-09python 基于UDP協(xié)議套接字通信的實現(xiàn)
這篇文章主要介紹了python 基于UDP協(xié)議套接字通信的實現(xiàn),幫助大家更好的理解和使用python,感興趣的朋友可以了解下2021-01-01Python version 2.7 required, which was not found in the regi
這篇文章主要介紹了安裝PIL庫時提示錯誤Python version 2.7 required, which was not found in the registry問題的解決方法,需要的朋友可以參考下2014-08-08