python——PEP8規範

python PEP8規範

一、    代碼佈局設計

1.1    縮進

  • 使用四個空格來進行縮進
  •  換行的時候可使用反斜槓,最好的方法是使用園括號,在使用反斜槓的時候,在反斜槓的後直接回車,不能有任何空格存在

比較好的作法以下:python

對準開始的分隔符:ide

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

包含更多的縮進表示是剩餘部分:函數

# More indentation included to distinguish this from the rest. def long_function_name( var_one, var_two, var_three, var_four): print(var_one)
  • 1
  • 2
  • 3
  • 4
  • 5

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

# Hanging indents should add a level. foo = long_function_name( var_one, var_two, var_three, var_four)
  • 1
  • 2
  • 3
  • 4

E:比較差的作法以下:(代碼一樣是能夠運行的)ui

# 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) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

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

         可選的以下:編碼

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

         當使用if語句的時候,若是條件剛好的縮進爲四個空格空格,那麼致使後面的語句的縮進也是四個空格,那麼這種狀況下是能夠接受的,以下所示:spa

         沒有額外的縮進:設計

# No extra indentation. if (this_is_one_thing and that_is_another_thing): do_something()
  • 1
  • 2
  • 3
  • 4

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

# 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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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

# 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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

         成對的小括號,中括號在多行的結構中能夠寫成多行,而後括號在第一個不爲空白的位置結束。以下:

my_list = [
    1, 2, 3, 4, 5, 6, ] result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f', )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

         或者對齊第一個字符的位置結束,以下:

my_list = [
    1, 2, 3, 4, 5, 6, ] result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f', )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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())
  • 1
  • 2
  • 3

確保在合適的時候將連續的行進行分開,最好的位置是操做符以後,而不是在操做符以前,以下:

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

1.4 空行

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

類中方法的定義空一行。

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

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

1.5 源文件編碼

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

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

1.6 導入

Import常用單獨的行,以下:

import os import sys
  • 1
  • 2

或者使用以下的方式:

from subprocess import Popen, PIPE
  • 1

Import老是在文件的最上行,在模塊的註釋和docstring以後,在模塊的全局變量以前。

Import能夠按照如下順序進行組織:

         A標準類庫import

         B第三方import

         C本地類庫import

在每一個組導入以後,能夠用空行進行分割

把全部 _ _ all __ 相關類型的聲明放在import以後

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

import mypkg.sibling from mypkg import sibling from mypkg.sibling import example
  • 1
  • 2
  • 3

對於複雜的封裝佈局來講,相對導入也是能夠接受的,主要是使用絕對導入的時候路徑太長,以下:

from . import sibling from .sibling import example
  • 1
  • 2

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

from myclass import MyClass from foo.bar.yourclass import YourClass
  • 1
  • 2

當以上的寫法致使本地名稱衝突,能夠寫成以下:

import myclass import foo.bar.yourclass
  • 1
  • 2

而且使用」myclass.MyClass」 and」foo.bar.yourclass.YourClass」。

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

from <module> import *
  • 1

二、    字符串引號

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

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

3.1 避免使用空格狀況

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

# Yes: spam(ham[1], {eggs: 2}) $# No: spam( ham[ 1 ], { eggs: 2 } )
  • 1
  • 2
  • 3
  • 4

B. 在逗號,分好,冒號以前不須要空格

# Yes: if x == 4: print x, y; x, y = y, x $# No: if x == 4 : print x , y ; x , y = y , x
  • 1
  • 2
  • 3
  • 4

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]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

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

# Yes: spam(1) $# No: spam (1)
  • 1
  • 2
  • 3
  • 4

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

# Yes: dct['key'] = lst[index] $# No: dct ['key'] = lst [index]
  • 1
  • 2
  • 3
  • 4

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

# Yes: x = 1 y = 2 long_variable = 3 $# No: x = 1 y = 2 long_variable = 3
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3.2 其餘建議

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

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

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

C. 若是操做符優先級不一樣,注意在操做符左右留空白,特別是高優先級和低優先級的

# 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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

四、    註釋

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

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

4.1 塊註釋

在一段代碼前增長註釋,在#後添加一個空格,段落之間只有一個#做爲行間隔

# Description : Module config. # # Input : None # # Output : None
  • 1
  • 2
  • 3
  • 4
  • 5

4.2 行註釋

在使用行註釋的時候,在代碼句子結束以後至少兩個空格,而後用#開頭後跟一個空格

x = x + 1 # Increment x But sometimes, this is useful: x = x + 1 # Compensate for border
  • 1
  • 2
  • 3

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

4.3 文檔註釋

在全部的公共模塊,函數,類,方法中加入文檔註釋,這些註釋寫在def以後。

在進行多行註釋的時候,注意「」「結束的時候,必須獨佔一行,以下:

"""Return a foobang Optional plotz says to frobnicate the bizbaz first. """ xxxxxxxxxx 
  • 1
  • 2
  • 3
  • 4

當文檔註釋是一行的時候,確保開始的「「」和「」「在同一行中。

五、    命名規範

使用單獨的小寫字母(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

類方法的靜態變量老是爲cls

若是一個方法的參數和保留字相沖突,那麼在後面添加下劃線進行區分

5.7 常量

常量命名所有使用大寫,可使用下劃線進行分割

六、    編碼建議

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

當實現比較的方法的時候,最好所有實現

eq , ne ,lt , le , gt , ge ),而不要單獨實現一個。

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

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

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

相關文章
相關標籤/搜索