天天看點

Python 常用 PEP8 編碼規範和建議

目錄

  • 代碼布局
    • 縮進
    • 最大行寬
    • 空行
    • 子產品導入
    • 字元串
    • 表達式和語句中的空格
    • 注釋
    • 命名規則
  • 程式設計建議

  • 每級縮進用4個空格。
  • 括号中使用垂直隐式縮進或使用懸挂縮進。

EXAMPLE:

# (垂直隐式縮進)對準左括号
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# (懸挂縮進) 一般情況隻需多一層縮進
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

# (懸挂縮進) 但下面情況, 需再加多一層縮進, 和後續的語句塊區分開來
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',
)           

錯誤示範:

# 不使用垂直對齊時,第一行不能有參數。
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# 參數的懸挂縮進和後續代碼塊縮進不能差別。
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 個字元
  • 一般續行可使用反斜杠
  • 括号内續行不需要使用反斜杠
# 無括号續行, 利用反斜杠
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())

# 括号内續行, 盡量在運算符後再續行
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))           

  • 兩行空行用于分割頂層函數和類的定義
  • 單個空行用于分割類定義中的方法
# 類的方法定義用單個空行分割,兩行空行分割頂層函數和類的定義。
class A(object):
    def method1():
        pass

    def method2():
        pass


def method3():
    pass           

  • 導入的每個子產品應該單獨成行
  • 導入順序如下: (各子產品類型導入之間要有空行分割,各組裡面的子產品的順序按子產品首字母自上而下升序排列)
    • 标準庫
    • 相關的第三方庫
    • 本地庫
# 按子產品首字母排序導入, 依此遞推
import active
import adidas
import create           

錯誤示例:

# 一行導入多子產品
import sys, os, knife

# 不按首字母導入
import create
import active
import beyond           

  • 單引号和雙引号作用是一樣的,但必須保證成對存在,不能夾雜使用.

    (建議句子使用雙引号, 單詞使用單引号, 但不強制.)

# 單引号和雙引号效果一樣
name = 'JmilkFan'
name = "Hey Guys!"           

  • 括号裡邊避免空格
spam(ham[1], {eggs: 2})           
spam( ham[ 1 ], { eggs: 2 } )           
  • 逗号,冒号,分号之前避免空格
if x == 4: print x, y; x, y = y, x           
if x == 4 : print x , y ; x , y = y , x           
  • 函數調用的左括号之前不能有空格
spam(1)
dct['key'] = lst[index]           
spam (1)
dct ['key'] = lst [index]           
  • 指派等操作符前後不能因為對齊而添加多個空格
x = 1
y = 2
long_variable = 3           
x             = 1
y             = 2
long_variable = 3           
  • 二進制運算符兩邊放置一個空格
    • 涉及 = 的複合操作符 ( += , -=等)
    • 比較操作符 ( == , < , > , != , <> , <= , >= , in , not in , is , is not )
    • 邏輯操作符( and , or , not )
a = b
a or b

# 括号内的操作符不需要空格
name = get_name(age, sex=None, city=Beijing)           

  • 注釋塊

    注釋塊通常應用在代碼前,并和代碼有同樣的縮進。每行以 ‘# ’ 開頭, 而且#後面有單個空格。

# 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])
           
  • 單行注釋(應避免無謂的注釋)
x = x + 1 # Compensate for border           
  • 文檔字元串
# 多行文檔, 首行首字母大寫,結尾的 """ 應該單獨成行
"""Return a foobang
Optional plotz says to frobnicate the bizbaz first.
"""

# 單行的文檔, 結尾的 """ 在同一行。
"""Return a foobang"""           

  • 包和子產品名:

    包和子產品名應該簡短,全部用小寫字母, 多字母之間可以使用單下劃線連接配接。

  • 類名:

    遵循駝峰命名

class MyClass(object):
    pass           
  • 全局變量名:

    全局變量名應盡量隻在子產品内部使用, 對可能使用語句

    from moduleName import variableName

    而被導入的子產品,應采用

    __all__

    機制來防止全局變量被别的子產品導入, 或者在全局變量名開頭加一個前置下劃線.
_name = 'name'           
  • 函數名

    函數名應該為全部小寫的凹駝峰規則。

vcenter_connection = ''           
  • 常量名

    常量全部使用大寫字母的凹駝峰規則來表示, 通常在子產品頂格定義

MAX_OVERFLOW = ''
TOTAL = 1           
  • 方法名和執行個體變量
    • 非公開方法和執行個體變量開頭使用前置下劃線
    • 有時候可能會為了避免與子類命名沖突,采用兩個前置下劃線

      需要注意的是: 若 class Foo 的屬性名為

      __a

      , 該屬性是不能以

      Foo.__a

      的方式通路的(執著的使用者還是可以通過

      Foo._Foo__a

      來通路), 是以通常雙前置下劃線僅被用來避免與基類的屬性發生命名沖突。
  • None 的比較用 is 或 is not,而不要用 ==
  • 用 is not 代替 not … is, 前者的可讀性更好
# Yes
if foo is not None

# No
if not foo is None           
  • 使用函數定義關鍵字 def 代替 lambda 指派給辨別符, 這樣更适合于回調和字元串表示
# Yes
def f(x): 
    return 2*x

# No
f = lambda x: 2*x           
  • 異常類應該繼承自Exception,而不是 BaseException
  • Python 2 中用

    raise ValueError('message')

    代替

    raise ValueError, 'message'

  • (考慮相容python3和續行的友善性)
  • 捕獲異常時盡量指明具體異常, 盡量不用

    except Exception

    , 應該捕獲 出了什麼問題,而不是 問題發生
# 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 子句中的代碼要盡可能的少, 以免屏蔽掉其他的錯誤
# 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)           
  • 函數或者方法在沒有傳回值時要明确傳回 None
# Yes
def foo():
    return None

# No
def foo():
    return           
  • 使用字元串方法而不是 string 子產品

    python 2.0 以後字元串方法總是更快,而且與 Unicode 字元串使用了相同的 API

  • 使用使用

    .startswith()

    .endswith()

    代替字元串切片來檢查字首和字尾

    startswith()

    endswith

    更簡潔,利于減少錯誤
# Yes
if foo.startswith('bar'):

# No
if foo[:3] == 'bar':           
  • 使用

    isinstance()

    代替對象類型的比較
# 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           
  • 不要用 == 進行 bool 比較
# Yes
if greeting:
   pass

# No
if greeting == True
   pass
if greeting is True: # Worse
   pass