PEP8 Python 編碼規范整理


(轉載自http://blog.csdn.net/kellyseeme/article/details/50644893)

1、    代碼布局設計

1.1    縮進

A、   使用四個空格來進行縮進

B、   換行的時候可以使用反斜杠,最好的方法是使用園括號,在使用反斜杠的時候,在反斜杠的后直接回車,不能有任何空格存在

 

比較好的做法如下:

 

對准開始的分隔符:

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
             var_three, var_four)

        

包含更多的縮進表示是剩余部分:

# More indentation included to distinguish this from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

 

         懸掛縮進應該添加一個級別:

# Hanging indents should add a level.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

 

比較差的做法如下:(代碼同樣是可以運行的)

# Arguments on first line forbidden when not using vertical alignment.—未使用垂直對齊
foo = long_function_name(var_one, var_two,
    var_three, var_four)
 
# Further indentation required as indentation is not distinguishable.(未使用縮進來表示每一層級)
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)

 

 

對於續行來說,四個空格的縮進是可選的。

         可選的如下:

# Hanging indents *may* be indented to other than 4 spaces.懸掛縮進的時候可以不是四個空格
foo = long_function_name(
  var_one, var_two,
  var_three, var_four)

 

 

         當使用if語句的時候,如果條件恰好的縮進為四個空格空格,那么導致后面的語句的縮進也是四個空格,那么這種情況下是可以接受的,如下所示:

         沒有額外的縮進:

# No extra indentation.
if (this_is_one_thing and
    that_is_another_thing):
    do_something()

 

         添加一個注釋來進行分割縮進,做到語法高亮顯示:

# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
    that_is_another_thing):
    # Since both conditions are true, we can frobnicate.
    do_something()

 

         在續行中添加額外的縮進:

# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
        and that_is_another_thing):
    do_something()

 

 

         成對的小括號,中括號在多行的結構中可以寫成多行,然后括號在第一個不為空白的位置結束。如下:

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 tab和空格的選擇

關於tab的空格的選擇,在python2中是可以混用的,但是在python3中,只能用一種風格。

 

1.3 最大行長度

行的最大長度為79個字符

 

在書寫文檔或者是注釋的時候,行長度應該控制在72個字符。

 

反斜杠在有的時候是適用的,例如在參數很長,但是不能隱式的使用多行的時候,如下反斜杠的使用:

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("values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

 

1.4 空行

Top level函數和類的定義的時候,空兩行。

類中方法的定義空一行。

 

在函數中謹慎使用空行來表示相關的邏輯段。

 

無關的函數之間用一個空行進行分割。

1.5 源文件編碼

在源文件中一直使用utf-8編碼,在python2中使用ascll編碼。

 

文件,在python2 中使用ascll編碼,在python3中使用utf-8編碼

1.6 導入

Import經常使用單獨的行,如下:

import os
import sys

或者使用如下的方式:

§ from subprocess import Popen, PIPE

 

Import總是在文件的最上行,在模塊的注釋和docstring之后,在模塊的全局變量之前。

Import可以按照以下順序進行組織:

         A標准類庫import

         B第三方import

         C本地類庫import

在每個組導入之后,可以用空行進行分割

把所有__all__相關類型的聲明放在import之后

 

推薦使用絕對導入,可讀性強,如下:

import mypkg.sibling

from mypkg import sibling

from mypkg.sibling import example

 

對於復雜的封裝布局來說,相對導入也是可以接受的,主要是使用絕對導入的時候路徑太長,如下:

from . import sibling

from .sibling import example

 

當導入一個類的時候,可以使用如下的方式:

from myclass import MyClass

from foo.bar.yourclass import YourClass

 

當以上的寫法導致本地名稱沖突,可以寫成如下:

import myclass

import foo.bar.yourclass

 

並且使用"myclass.MyClass" and"foo.bar.yourclass.YourClass"。

 

在導入模塊的時候,應該避免通配符的存在,如下:

from <module> import *

 

2、    字符串引號

在對於字符串的標示中,使用雙引號還是單引號是沒有區別的,主要就是兩者混合使用從而避免反斜杠的出現。

3、    在表達式和語句中使用空格

3.1 避免使用空格情況

A. 在小括號,中括號,大括號中避免使用空格

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

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

 

B. 在逗號,分好,冒號之前不需要空格

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

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

 

C. 在切片的時候,避免使用空格,在擴展的切片中,必須使用相同的空格個數,如下所示:

Yes:

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]

No:

ham[lower + offset:upper + offset]

ham[1: 9], ham[1 :9], ham[1:9 :3]

ham[lower : : upper]

ham[ : upper]

 

 

D.函數的左括號前不要添加空格:

Yes: spam(1)

No:  spam (1)

 

E. 中括號前不要添加空格

Yes: dct['key'] = lst[index]

No:  dct ['key'] = lst [index]

 

 

F. 操作符左右各一個空格,不要為了追求一致從而添加空格個數

Yes:

x = 1

y = 2

long_variable = 3

No:

x             = 1

y             = 2

long_variable = 3

 

3.2 其他建議

A. 避免在任何結尾添加空白。

 

B. 在下列操作符中左右各留空白

assignment ( = ), augmented assignment ( += , -= etc.), comparisons ( == , < , > , != , <> , <= , >= , in , not in , is , is not ), Booleans ( and , or , not )

 

C. 如果操作符優先級不同,注意在操作符左右留空白,特別是高優先級和低優先級的

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)

 

 

D. 在使用函數的時候,賦值和默認值之間不需要空格

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)

 

 

E. 不要將多語句寫在同一行

Rather not:

if foo == 'blah': do_blah_thing()

for x in lst: total += x

while t < 10: t = delay()

Definitely not:

if foo == 'blah': do_blah_thing()

else: do_non_blah_thing()

 

try: something()

finally: cleanup()

 

do_one(); do_two(); do_three(long, argument,

                             list, like, this)

 

if foo == 'blah': one(); two(); three()

 

4、    注釋

在修改的代碼的時候,務必修改注釋。

注釋必須是英文,最好是完整的句子,首字母大寫

4.1 塊注釋

在一段代碼前增加注釋,在#后添加一個空格,段落之間只有一個#作為行間隔

# Description : Module config.

#

# Input : None

#

# Output : None

4.2 行注釋

在使用行注釋的時候,在代碼句子結束之后至少兩個空格,然后用#開頭后跟一個空格

x = x + 1                 # Increment x

But sometimes, this is useful:

x = x + 1                 # Compensate for border

 

在上面例子中,表示不要使用無效注釋,主要是說明其目的

4.3 文檔注釋

在所有的公共模塊,函數,類,方法中加入文檔注釋,這些注釋寫在def之后。

 

在進行多行注釋的時候,注意“”“結束的時候,必須獨占一行,如下:

"""Return a foobang

 

Optional plotz says to frobnicate the bizbaz first.

"""

 

 

當文檔注釋是一行的時候,確保開始的““”和“”“在同一行中。

 

5、    命名規范

使用單獨的小寫字母(b)

使用單獨的大寫字母(B)

使用小寫字母(lowercase)

使用小寫字母和下划線(lower_case_with_underscores)

使用大寫字母(UPPERCASE)

使用大寫字母和下划線(UPPER_CASE_WITH_UPPERCASE)

駝峰式寫法(CamelCase):在使用縮寫的時候,大寫優於小寫例如HTTPServer優於HttpServer

首字母大寫,然后使用下划線是一種丑陋的寫法

5.1 避免使用的名稱

在寫變量的時候,盡量避免小寫的l和大寫字母O和大寫字母I,主要原因是容易和數字中1,0相混淆

5.2 包和模塊名稱

模塊盡量使用簡短的全部小寫的名稱,如果可以增加可讀性那么可以使用下划線,python的包不推薦使用下划線,但是在引用其他語言寫的擴展包中可以使用下划線來表示區分

5.3 類名稱

類名稱主要遵循為CapWords約定,表示為首字母大寫

 

5.4 異常名稱

異常歸於類,從而也要遵循類名的規范,主要是在后綴上必須添加“Error“

5.4 全局變量名

全局變量只在模塊類有效,和function命名相同

5.5 方法名稱

方法名稱全部為小寫,下划線是可選的(在增加可讀性的基礎上使用)

5.6 方法變量

類的方法第一個參數總是self

類方法的靜態變量總是為crs

如果一個方法的參數和保留字相沖突,那么在后面添加下划線進行區分

5.7 常量

常量命名全部使用大寫,可以使用下划線進行分割

6、    編碼建議

單獨比較的時候使用is或者is not,不要使用==進行比較。

 

當實現比較的方法的時候,最好全部實現

__eq__ , __ne__ ,__lt__ , __le__ , __gt__ , __ge__ ),而不要單獨實現一個。

使用startswith() and endswith()代替切片進行序列前綴或后綴的檢查。比如

Yes: if foo.startswith(‘bar’):優於

No: if foo[:3] == ‘bar’:

7 使用isinstance()比較對象的類型。比如
Yes: if isinstance(obj, int): 優於
No: if type(obj) is type(1):


免責聲明!

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



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