python代碼格式規范


目前的規范基於pep-0008

基本格式

縮進

使用4個空格進行縮進

行寬

每行代碼盡量不超過80個字符

理由:

  • 這在查看side-by-side的diff時很有幫助
  • 方便在控制台下查看代碼
  • 太長可能是設計有缺陷

換行

Python支持括號內的換行。這時有兩種情況。

  1. 第二行縮進到括號的起始處
foo = long_function_name(var_one, var_two,
                         var_three, var_four)
  1. 第二行縮進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

比較

  • 使用變量在左,常量在右
  • 不顯示進行對TrueFalse的比較
  • 否定比較采用,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 中有詳細描述,其中最其本的兩點:

  1. 所有的公共模塊、函數、類、方法,都應該寫docstring。私有方法不一定需要,但應該在def后提供一個塊注釋來說明。
  2. docstring的結束"""應該獨占一行,除非此docstring只有一行。
"""Return a foobar Optional plotz says to frobnicate the bizbaz first. """ """Oneline docstring"""

命名規范

  • 應避免使用小寫字母l(L),大寫字母O(o)I(i)單獨作為一個變量的名稱,以區分數字10
  • 包和模塊使用全小寫命名,盡量不要使用下划線
  • 類名使用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: cls as first parameter.
  • Instance methods: self as first parameter.
  • Lambdas for properties may have the first parameter replaced with x, as in display_name = property(lambda x: x.real_name or x.username).

編碼

  • 文件使用UTF-8編碼
  • 文件頭部加入#-*-coding:utf-8-*-標識


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM