目前的規范基於pep-0008
基本格式
縮進
使用4個空格進行縮進
行寬
每行代碼盡量不超過80個字符
理由:
- 這在查看side-by-side的diff時很有幫助
- 方便在控制台下查看代碼
- 太長可能是設計有缺陷
換行
Python支持括號內的換行。這時有兩種情況。
- 第二行縮進到括號的起始處
foo = long_function_name(var_one, var_two,
var_three, var_four)
- 第二行縮進4個空格,適用於起始括號就換行的情形
def long_function_name( var_one, var_two, var_three, var_four): print(var_one)
使用反斜杠\換行,二元運算符+ .等應出現在行首,並與上一行的.或=對齊;或者縮進4個空格。長字符串也可以用此法換行
foo = variable_with_long_name \
+ another_variable \ + variable session.query(MyTable) \ .filter_by(id=1) \ .one() this_is_a_very_long(function_call, 'with many parameters') \ .that_returns_an_object_with_an_attribute print 'Hello, ' \ '%s %s!' % \ ('Harry', 'Potter')
多個元素的list或者tuple,在起始括號后換行,第二行縮進4個空格
items = [
'this is the first', 'set of items', 'with more items', 'to come in this line', 'like this' ]
禁止復合語句,即一行中包含多個語句:
# yes do_first() do_second() do_third() # no do_first();do_second();do_third();
if/for/while一定要換行:
# yes if foo == 'blah': do_blah_thing() # no if foo == 'blah': do_blash_thing()
空行
- 模塊級函數和類定義之間空兩行;
- 類成員函數之間空一行;
- 不要使用太多的連續空行來區分代碼的邏輯塊
class A: """This is a simple docstring.""" def __init__(self): pass def hello(self): pass def hello(name): print "Hello %s!" % name def main(): pass
- 可以使用多個空行分隔多組相關的函數
- 函數中可以使用空行分隔出邏輯相關的代碼
表達式
空格
- 一元運算符不加空格
- 在二元運算符兩邊各空一格
[=,-,+=,==,>,in,is not, and]:
# yes exp = -1.05 i = i + 1 submitted += 1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) # no exp = - 1.05 i=i+1 submitted +=1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b)
- 函數的參數列表中,
,之后要有空格
# yes def complex(real, imag): pass # no def complex(real,imag): pass
- 函數的參數列表中,默認值等號兩邊不要添加空格
# yes def complex(real, imag=0.0): pass # no def complex(real, imag = 0.0): pass
- 左括號之后,右括號之前不要加多余的空格
# yes spam(ham[1], {eggs: 2}) value = my_list[index] # no spam( ham[1], { eggs : 2 } ) value = my_list[ index ]
- 字典、列表對象的左括號之前不要多余的空格
# yes dict['key'] = list[index] # no dict ['key'] = list [index]
- 不要為對齊賦值語句而使用的額外空格
# yes x = 1 y = 2 long_variable = 3 # no x = 1 y = 2 long_variable = 3
比較
- 使用變量在左,常量在右
- 不顯示進行對
True、False的比較 - 否定比較采用,
foo not in bar的形式,而不是not foo in bar - 使用
instance(a, C)進行實例的類型檢查,而不是type(A) is C
# yes if method == 'md5': pass if not foo: pass if foo not in bar: pass if instance(a, C): pass # no if 'md5' == method: pass if foo == False: pass if not foo in bar: pass if type(A) is C: pass
引號
簡單說,自然語言使用雙引號,機器標示使用單引號,因此 代碼里 多數應該使用 單引號
- 自然語言 使用雙引號
"..."
例如錯誤信息;很多情況還是unicode,使用u"你好世界" - 機器標識 使用單引號
'...'例如dict里的key - 正則表達式 使用原生的雙引號
r"..." - 文檔字符 使用三個雙引號
"""......"""
import語句
- import語句應該分行書寫
# yes import os import sys # no import sys,os # yes from subprocess import Popen, PIPE
- import語句應該使用 absolute import
# yes from foo.bar import Bar # no from ..bar import Bar
- import語句應該放在文件頭部,置於模塊說明及docstring之后,於全局變量之前;
- import語句應該按照順序排列,每組之間用空行分隔
import os
import sys import msgpack import zmq import foo
- 導入其他模塊的類定義時,可以使用相對導入
from myclass import MyClass
- 如果發生命名沖突,則可使用命名空間
import bar
import foo.bar bar.Bar() foo.bar.Bar()
注釋
塊注釋
#號后空一格,段落間用空行分開(同樣需要#號)
# 塊注釋 # 塊注釋 # # 塊注釋 # 塊注釋
行注釋
至少使用兩個空格和語句分開,使用有意義的注釋
# yes x = x + 1 # 邊框加粗一個像素 # no x = x + 1 # x加1
docstring
docstring的規范在 PEP 257 中有詳細描述,其中最其本的兩點:
- 所有的公共模塊、函數、類、方法,都應該寫docstring。私有方法不一定需要,但應該在def后提供一個塊注釋來說明。
- docstring的結束"""應該獨占一行,除非此docstring只有一行。
"""Return a foobar Optional plotz says to frobnicate the bizbaz first. """ """Oneline docstring"""
命名規范
- 應避免使用小寫字母
l(L),大寫字母O(o)或I(i)單獨作為一個變量的名稱,以區分數字1和0 - 包和模塊使用全小寫命名,盡量不要使用下划線
- 類名使用
CamelCase命名風格,內部類可用一個下划線開頭;
約定的縮寫保留原樣,例如使用HTTPWriter而不是HttpWriter - 函數使用下划線分隔的小寫命名,
lowercase_with_underscores - 當參數名稱和Python保留字沖突,可在最后添加一個下划線,盡量不是使用縮寫或自造的詞
- 常量使用以下划線分隔的大寫命名,
UPPERCASE_WITH_UNDERSCORES - Precompiled regular expressions:
name_re
MAX_OVERFLOW = 100 Class FooBar: def foo_bar(self, print_): print(print_)
Function and method arguments:
- Class methods:
clsas first parameter. - Instance methods:
selfas first parameter. - Lambdas for properties may have the first parameter replaced with
x, as indisplay_name = property(lambda x: x.real_name or x.username).
編碼
- 文件使用UTF-8編碼
- 文件頭部加入
#-*-coding:utf-8-*-標識
