對于python而言,官方的PEP8規(guī)范是使用最廣泛缤削,認(rèn)可度最高的代碼規(guī)范窘哈,具體可訪問:PEP 8
在線Python代碼規(guī)范
1 代碼布局
1.1 縮進(jìn):多行代碼的縮進(jìn)與對齊
我的個人習(xí)慣是用制表符(4個空格)
多行結(jié)構(gòu)上的閉大括號/尖括號/圓括號可以對齊到列表最后一行的第一個非空白字符下
my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)
或者:
my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)
1.2 最大的行寬:79
官方建議:限制行最大字符數(shù)為 79 。如何過長需要通過 "" 或者括號(圓括號亭敢,中括號滚婉,花括號)進(jìn)行換行
使用括號進(jìn)行換行,第二行第一個字符需要與括號里的第一個字符對齊
x = ('This is a test '
'for python style')
無法使用括號的帅刀,則通過“\" 進(jìn)行換行
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())
1.3 二元操作符的連接與換行
錯誤的寫法
# Wrong:
# operators sit far away from their operands
income = (gross_wages +
taxable_interest +
(dividends - qualified_dividends) -
ira_deduction -
student_loan_interest)
正確的寫法:視線不用跨越兩行让腹,能夠直觀的看出對變量進(jìn)行的操作
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)
1.4 空行的使用
- 模塊級函數(shù)和類定義之間空兩行
- 類成員函數(shù)之間空一行
- 可以使用多個空行分隔多組相關(guān)的函數(shù)
- 函數(shù)中可以使用空行分隔出邏輯相關(guān)的代碼
class A:
def __init__(self):
pass
def hello(self):
pass
def main():
pass
1.5 編碼
python3 默認(rèn)編碼 UTF-8,python2 默認(rèn)編碼 ASCII 扣溺。使用默認(rèn)編碼不需要聲明
若 python2 中需要使用UTF-8編碼骇窍,需要在文件頭部加入 #--conding:utf-8--
1.6 import模塊導(dǎo)入
import語句應(yīng)該放在文件頭部,置于模塊說明及docstring之后锥余,于全局變量之前腹纳;
模塊導(dǎo)入順序:不同類型的模塊之間最好用空行進(jìn)行分割
1.標(biāo)準(zhǔn)模塊
2.第三方模塊
3.自編模塊import 語句應(yīng)該分行來寫
# Correct:
import os
import sys
# Wrong: 也不是不能用,是不推薦
import sys, os
- 推薦使用絕對路徑導(dǎo)入:
# Correct:
from subprocess import Popen, PIPE復(fù)制代碼
import語句應(yīng)該使用 absolute import
# Correct:
from foo.bar import Bar
# Wrong
from ..bar import Bar
- 當(dāng)從包含類的模塊中導(dǎo)入一個類時
from myclass import MyClass
from foo.bar.yourclass import YourClass
- 如果發(fā)生命名沖突,則可使用命名空間
import bar
import foo.bar
bar.Bar()
foo.bar.Bar()
1.7 書寫順序
- 文檔說明:docstring在最前面嘲恍,接著是下劃線開頭或者結(jié)尾的模塊及變量足画,然后是標(biāo)準(zhǔn)模塊導(dǎo)入等的
"""This is the example module.
This module does stuff.
"""
from __future__ import barry_as_FLUFL
__all__ = ['a', 'b', 'c']
__version__ = '0.1'
__author__ = 'Cardinal Biggles'
import os
import sys
2 字符串引號
單引號或者雙引號都是可以的,根據(jù)自己的習(xí)慣佃牛。當(dāng)字符串中本身包含單引號或者雙引號時淹辞,可以選擇另外一個,避免使用 \l來進(jìn)行轉(zhuǎn)義
3 表達(dá)式和語句中的空格
3.1 以下情況不需要出現(xiàn)空格
- 方括號俘侠、中括號象缀、大括號內(nèi)不需要空格
# Correct:
spam(ham[1], {eggs: 2})
# Wrong:
spam( ham[ 1 ], { eggs: 2 } )
- 末尾,和 ) 之間 不需要空格
# Correct:
foo = (0,)
# Wrong:
bar = (0, )
- 逗號兼贡、分號攻冷、冒號前不需要空格
# Correct:
if x == 4: print x, y; x, y = y, x
# Wrong:
if x == 4 : print x , y ; x , y = y , x
- 切片左右的空格可以被省略
# Correct:
ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
ham[lower:upper], ham[lower:upper:], ham[lower::step]
ham[lower+offset : upper+offset]
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
ham[lower + offset : upper + offset]
# Wrong:
ham[lower + offset:upper + offset]
ham[1: 9], ham[1 :9], ham[1:9 :3]
ham[lower : : upper]
ham[ : upper]
- 函數(shù)調(diào)用 ( 前不需要空格
# Correct:
spam(1)
# Wrong:
spam (1)
- 不要為了對齊而增加多余的空格
# Correct:
x = 1
y = 2
long_variable = 3
# Wrong:
x = 1
y = 2
long_variable = 3
*其他建議:
- 不要存在拖尾空格
- 反斜杠后面不要存在空格或者空行
- 二次運算符左右兩邊各需要一個空格: =,+=, -= ,==, <, >, !=, <>, <=, >=, in, not in, is, is not,and, or, not
# Correct:
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)
# Wrong:
i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
- 當(dāng)用于指示關(guān)鍵字參數(shù)或用于指示未帶注釋的函數(shù)形參的默認(rèn)值時,不要在=符號周圍使用空格
# Correct:
def complex(real, imag=0.0):
return magic(r=real, i=imag)
# Wrong:
def complex(real, imag = 0.0):
return magic(r = real, i = imag)
- 不建議使用復(fù)合語句
# Correct:
if foo == 'blah':
do_blah_thing()
do_one()
do_two()
do_three()
Rather not:
# Wrong:
if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()
# Wrong:
if foo == 'blah': do_blah_thing()
for x in lst: total += x
while t < 10: t = delay()
4 末尾逗號的使用
- 一般末尾不需要加逗號
# Correct:
FILES = ('setup.cfg',)
# Wrong:
FILES = 'setup.cfg',
- 多行時可以加逗號遍希,一行時就不需要加逗號了
# Correct:
FILES = [
'setup.cfg',
'tox.ini',
]
initialize(FILES,
error=True,
)
# Wrong:
FILES = ['setup.cfg', 'tox.ini',]
initialize(FILES, error=True,)
5 注釋
5.1 塊注釋 : # 號后空一格致板,段落件用空行分開(同樣需要“#”號)
# something
# something
#
# something
# something
5.2 行注釋:至少使用兩個空格和語句分開,注意不要使用無意義的注釋
x = x + 1 # Compensate for border
5.3 文檔注釋:
作為文檔的Docstring一般出現(xiàn)在模塊頭部哼审、函數(shù)和類的頭部绝编,python中可以通過對象的doc對象獲取文檔.
- 文檔注釋以 """ 開頭和結(jié)尾, 首行不換行, 如有多行, 末行必需換行, 以下是Google的docstring風(fēng)格示例
- 不要在文檔注釋復(fù)制函數(shù)定義原型, 而是具體描述其具體內(nèi)容, 解釋具體參數(shù)和返回值等
6 命名規(guī)范
- 不要使用 'l' , 'O', 'I'
- 模塊(或函數(shù))的命名應(yīng)該全部都是小寫,多個單詞之間用下劃線分割即可废封,不過盡量簡短
- 類的命名可使用用駝峰(ClassAbc)州泊,首字母大寫,私有類可用一個下劃線開頭
- 函數(shù)的命名最好小寫漂洋,如有多個單詞遥皂,用下劃線隔開
- 變量名盡量小寫, 如有多個單詞,用下劃線隔開
- 常量使用以下劃線分隔的大寫命名