縮進(jìn)
每級(jí)縮進(jìn)用4個(gè)空格。
括號(hào)中使用垂直隱式縮進(jìn)或使用懸掛縮進(jìn)。
EXAMPLE:
# (垂直隱式縮進(jìn))對(duì)準(zhǔn)左括號(hào)
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ù)的語(yǔ)句塊區(qū)分開(kāi)來(lái)
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
# 右括號(hào)回退
my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)
錯(cuò)誤示范:
# 不使用垂直對(duì)齊時(shí),第一行不能有參數(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)
# 右括號(hào)不回退,不推薦
my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)
最大行寬
每行最大行寬不超過(guò) 79 個(gè)字符
一般續(xù)行可使用反斜杠
括號(hào)內(nèi)續(xù)行不需要使用反斜杠
EXAMPLE:
# 無(wú)括號(hào)續(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())
# 括號(hào)內(nèi)續(xù)行, 盡量在運(yùn)算符后再續(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ù)和類的定義
單個(gè)空行用于分割類定義中的方法
EXAMPLE:
# 類的方法定義用單個(gè)空行分割,兩行空行分割頂層函數(shù)和類的定義。
class A(object):
def method1():
pass
def method2():
pass
def method3():
pass
模塊導(dǎo)入
導(dǎo)入的每個(gè)模塊應(yīng)該單獨(dú)成行
導(dǎo)入順序如下: (各模塊類型導(dǎo)入之間要有空行分割,各組里面的模塊的順序按模塊首字母自上而下升序排列)
標(biāo)準(zhǔn)庫(kù)
相關(guān)的第三方庫(kù)
本地庫(kù)
EXAMPLE:
# 按模塊首字母排序?qū)? 依此遞推
import active
import adidas
import create
錯(cuò)誤示例:
# 一行導(dǎo)入多模塊
import sys, os, knife
# 不按首字母導(dǎo)入
import create
import active
import beyond
字符串
單引號(hào)和雙引號(hào)作用是一樣的,但必須保證成對(duì)存在,不能夾雜使用.
(建議句子使用雙引號(hào), 單詞使用單引號(hào), 但不強(qiáng)制.)
EXAMPLE:
# 單引號(hào)和雙引號(hào)效果一樣
name = 'JmilkFan'
name = "Hey Guys!"
表達(dá)式和語(yǔ)句中的空格
括號(hào)里邊避免空格
EXAMPLE:
spam(ham[1], {eggs: 2})
錯(cuò)誤示例:
spam( ham[ 1 ], { eggs: 2 } )
逗號(hào),冒號(hào),分號(hào)之前避免空格
EXAMPLE:
if x == 4: print x, y; x, y = y, x
錯(cuò)誤示例:
if x == 4 : print x , y ; x , y = y , x
函數(shù)調(diào)用的左括號(hào)之前不能有空格
EXAMPLE:
spam(1)
dct['key'] = lst[index]
錯(cuò)誤示例:
spam (1)
dct ['key'] = lst [index]
賦值等操作符前后不能因?yàn)閷?duì)齊而添加多個(gè)空格
EXAMPLE:
x = 1
y = 2
long_variable = 3
錯(cuò)誤示例:
x = 1
y = 2
long_variable = 3
二元運(yùn)算符兩邊放置一個(gè)空格
涉及 = 的復(fù)合操作符 ( += , -=等)
比較操作符 ( == , < , > , != , <> , <= , >= , in , not in , is , is not )
邏輯操作符( and , or , not )
EXAMPLE:
a = b
a or b
# 括號(hào)內(nèi)的操作符不需要空格
name = get_name(age, sex=None, city=Beijing)
注釋
注釋塊
注釋塊通常應(yīng)用在代碼前,并和代碼有同樣的縮進(jìn)。每行以 ‘# ’ 開(kāi)頭, 而且#后面有單個(gè)空格。
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)避免無(wú)謂的注釋)
EXAMPLE:
x = x + 1 # Compensate for border
文檔字符串
EXAMPLE:
# 多行文檔, 首行首字母大寫(xiě),結(jié)尾的 """ 應(yīng)該單獨(dú)成行
"""Return a foobang
Optional plotz says to frobnicate the bizbaz first.
"""
# 單行的文檔, 結(jié)尾的 """ 在同一行。
"""Return a foobang"""
命名規(guī)則
包和模塊名:
包和模塊名應(yīng)該簡(jiǎn)短,全部用小寫(xiě)字母, 多字母之間可以使用單下劃線連接。
類名:
遵循駝峰命名
class MyClass(object):
pass
全局變量名:
全局變量名應(yīng)盡量只在模塊內(nèi)部使用, 對(duì)可能使用語(yǔ)句 from moduleName import variableName 而被導(dǎo)入的模塊,應(yīng)采用 __all__ 機(jī)制來(lái)防止全局變量被別的模塊導(dǎo)入, 或者在全局變量名開(kāi)頭加一個(gè)前置下劃線.
EXAMPLE:
name = 'name'
函數(shù)名
函數(shù)名應(yīng)該為全部小寫(xiě)的凹駝峰規(guī)則。
EXAMPLE:
vcenter_connection = ''
常量名
常量全部使用大寫(xiě)字母的凹駝峰規(guī)則來(lái)表示, 通常在模塊頂格定義
EXAMPLE:
MAX_OVERFLOW = ''
TOTAL = 1
方法名和實(shí)例變量
非公開(kāi)方法和實(shí)例變量開(kāi)頭使用前置下劃線
有時(shí)候可能會(huì)為了避免與子類命名沖突,采用兩個(gè)前置下劃線
需要注意的是: 若 class Foo 的屬性名為 __a, 該屬性是不能以 Foo.__a 的方式訪問(wèn)的(執(zhí)著的用戶還是可以通過(guò)Foo._Foo__a 來(lái)訪問(wèn)), 所以通常雙前置下劃線僅被用來(lái)避免與基類的屬性發(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)識(shí)符, 這樣更適合于回調(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ù)行的方便性)
捕獲異常時(shí)盡量指明具體異常, 盡量不用 except Exception, 應(yīng)該捕獲 出了什么問(wèn)題,而不是 問(wèn)題發(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 子句中的代碼要盡可能的少, 以免屏蔽掉其他的錯(cuò)誤
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:
# 可能會(huì)捕捉到 handle_value()中的 KeyError, 而不是 collection 的
return key_not_found(key)
函數(shù)或者方法在沒(méi)有返回值時(shí)要明確返回 None
# Yes
def foo():
return None
# No
def foo():
return
使用字符串方法而不是 string 模塊
python 2.0 以后字符串方法總是更快,而且與 Unicode 字符串使用了相同的 API
使用使用 .startswith() 和 .endswith() 代替字符串切片來(lái)檢查前綴和后綴
startswith() 和 endswith 更簡(jiǎn)潔,利于減少錯(cuò)誤
EXAMPLE:
# Yes
if foo.startswith('bar'):
# No
if foo[:3] == 'bar':
使用 isinstance() 代替對(duì)象類型的比較
EXAMPLE:
# Yes
if isinstance(obj, int):
# No
if type(obj) is type(1):
空序列類型對(duì)象的 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
評(píng)論