1. 程式人生 > >Python PEP8 編碼規範 表達式和語句中的空格

Python PEP8 編碼規範 表達式和語句中的空格

pytho 所有 set input 自己 避免 spam 語句塊 混亂

不能忍受的事情

在下列情況下,避免使用無關的空格:

  • 緊跟在小括號,中括號或者大括號後。
Yes: spam(ham[1], {eggs: 2})
No:  spam( ham[ 1 ], { eggs: 2 } )
  • 緊貼在逗號、分號或者冒號之前。
Yes: if x == 4: print x, y; x, y = y, x
No:  if x == 4 : print x , y ; x , y = y , x
  • 然而,冒號在切片中就像二元運算符,在兩邊應該有相同數量的空格(把它當做優先級最低的操作符)。在擴展的切片操作中,所有的冒號必須有相同的間距。例外情況:當一個切片參數被省略時,空格就被省略了。
    推薦:

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]

  不推薦

ham[lower + offset:upper + offset]
ham[1: 9], ham[1 :9], ham[1:9 :3]
ham[lower : : upper]
ham[ : upper]
  • 緊貼在函數參數的左括號之前。
Yes: spam(1)
No:  spam (1)
  • 緊貼索引或者切片的左括號之前。
Yes: dct[‘key‘] = lst[index]
No:  dct [‘key‘] = lst [index]
  • 為了和另一個賦值語句對齊,在賦值運算符附件加多個空格。
    推薦:
x = 1
y = 2
long_variable = 3

不推薦:

x             = 1
y             = 2
long_variable = 3

其他建議

  • 避免在尾部添加空格。因為尾部的空格通常都看不見,會產生混亂:比如,一個反斜杠後面跟一個空格的換行符,不算續行標記。有些編輯器不會保留尾空格,並且很多項目(像CPython)在pre-commit的掛鉤調用中會過濾掉尾空格。
  • 總是在二元運算符兩邊加一個空格:賦值(=),增量賦值(+=,-=),比較(==,<,>,!=,<>,<=,>=,in,not,in,is,is not),布爾(and, or, not)。
  • 如果使用具有不同優先級的運算符,請考慮在具有最低優先級的運算符周圍添加空格。有時需要通過自己來判斷;但是,不要使用一個以上的空格,並且在二元運算符的兩邊使用相同數量的空格。
    推薦:
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

不推薦:

i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
  • 在制定關鍵字參數或者默認參數值的時候,不要在=附近加上空格。
    推薦:
def complex(real, imag=0.0):
    return magic(r=real, i=imag)

不推薦:

def complex(real, imag = 0.0):
    return magic(r = real, i = imag)
  • 功能型註釋應該使用冒號的一般性規則,並且在使用->的時候要在兩邊加空格。(參考下面的功能註釋得到能夠多信息)
    推薦:
def munge(input: AnyStr): ...
def munge() -> AnyStr: ...

不推薦:

def munge(input:AnyStr): ...
def munge()->PosInt: ...
  • 當給有類型備註的參數賦值的時候,在=兩邊添加空格(僅針對那種有類型備註和默認值的參數)。
    推薦:
def munge(sep: AnyStr = None): ...
def munge(input: AnyStr, sep: AnyStr = None, limit=1000): ...

不推薦:

def munge(input: AnyStr=None): ...
def munge(input: AnyStr, limit = 1000): ...
  • 復合語句(同一行中的多個語句)通常是不允許的。
    推薦:
if foo == ‘blah‘:
    do_blah_thing()
do_one()
do_two()
do_three()

不推薦:

if foo == ‘blah‘: do_blah_thing()
do_one(); do_two(); do_three()
  • 雖然有時候將小的代碼塊和 if/for/while 放在同一行沒什麽問題,多行語句塊的情況不要這樣用,同樣也要避免代碼行太長!
    最好別這樣:
if foo == ‘blah‘: do_blah_thing()
for x in lst: total += x
while t < 10: t = delay()

不推薦:

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()

Python PEP8 編碼規範 表達式和語句中的空格