天天看點

PEP8 中文翻譯,python的程式設計規範注釋命名

英文原文位址:

http://legacy.python.org/dev/peps/pep-0008/

原文太長,這裡展示一部分規範。

介紹

本文檔改編自《Guido's original Python Style Guide essay》,還有一些來自《Barry's style guide》

一緻性并不一定對(A Foolish Consistency is the Hobgoblin of Little Minds)

代碼更多的是為了讓人去讀。

一緻性很重要。但是更重要的是:知道何時保持一緻性,很多時候不應該用代碼規範。

下面的情況忽略掉代碼規範:

  • 當用上代碼規範後,讓代碼不容易閱讀。
  • 和周圍代碼保持一直(可能是曆史代碼)
  • 由于代碼的原因,沒有任何理由修改代碼(除了使用代碼規範)
  • 與舊版本保持一直,或不支援代碼規範中的寫法

代碼布局

Indentation(縮進)

使用4個空格

下面是帶括号的一些縮進情況。

Yes:

# 和括号開始的部分對齊
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)
           

No:

# 禁止對齊下一層的代碼
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)
           

還可以用下面的風格:

# 不需要額外的縮進
foo = long_function_name(
  var_one, var_two,
  var_three, var_four)
           

在閉合的括号中,可以選擇下面兩種方式,都行:

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',
)
           

空格或者Tab

空格是絕對的首選。

python3 已經不允許空格和Tab混用了。

每行最大字元數

修改每行最大字元數到79,因為python标準庫就是每行最大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))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)
           

源碼檔案的編碼

python2 預設ASCII ,python3 預設utf8

用utf8省事

import的使用

分行包含:

Yes: import os
     import sys

No:  import sys, os
           

下面的也可以:

from subprocess import Popen, PIPE
           

包含順序也有講究,順序如下(他們之間最好加一個換行):

  • 标準庫
  • 第三方庫
  • 本地的應用或者庫

使用絕對路徑import,不用import *  ,可能會導入到名字相同的沖突的包

表達式和語句中的空格

避免多餘的空格

1.括号裡:

Yes: spam(ham[1], {eggs: 2})
No:  spam( ham[ 1 ], { eggs: 2 } )
           

2.逗号,冒号,分号 之後:

Yes: if x == 4: print x, y; x, y = y, x
No:  if x == 4 : print x , y ; x , y = y , x
           

3.方法調用:

Yes: spam(1)
No:  spam (1)
           

4.數組索引

Yes: dict['key'] = list[index]
No:  dict ['key'] = list [index]
           

5.多個指派(或其他)操作:

Yes:

x = 1
y = 2
long_variable = 3
           

No:

x             = 1
y             = 2
long_variable = 3
           

其它建議

1.對于 assignment (=),augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).,需要加上空格

Yes:

i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)
           

No:

i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
           

2.當=用于給參數賦預設值的時候,不要加空格

Yes:

def complex(real, imag=0.0):
    return magic(r=real, i=imag)
           

No:

def complex(real, imag = 0.0):
    return magic(r = real, i = imag)
           

3.多操作的時候,要換行

Yes:

if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()
           

Rather not:

if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()
           

注釋

優先更新注釋,用英語寫

命名

1.子產品名短一點,都小寫,用下劃線。因為子產品會映射到檔案的名字,是以避免和系統限制沖突(大小寫不區分,長度限制等)

2.類名:首字母大寫,内部類加入前導下劃線

3.異常名:加入字尾Error

4.函數名:小寫+下劃線

5.函數和方法的參數:執行個體使用self 開始,類使用cls 開始。如果和系統參數名重複,在其後加_

6.方法名和執行個體變量:小寫+下劃線

結束