#括号紧跟的前后
Yes: spam(ham[1], {eggs: 2})
No: spam( ham[ 1 ], { eggs: 2 } )
#逗号加反括号
Yes: foo = (0,)
No: bar = (0, )
#逗号,分号,冒号前
Yes: if x == 4: print x, y; x, y = y, x
No: if x == 4 : print x , y ; x , y = y , x
#切片中的特殊情况:如果有表达式,应保证冒号左右对称(数字不加空格)
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]
#函数或变量的左括号,索引或切片均不加空格
Yes: spam(1)
No: spam (1)
Yes: dct['key'] = lst[index]
No: dct ['key'] = lst [index]
#等号两边各加一个空格,不可为了对其而多加
Yes:
x = 1
y = 2
long_variable = 3
No:
x = 1
y = 2
long_variable = 3
#这些运算符左右各加一个空格: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)
#关键字或默认赋值时的等号不添加空格:
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)
#函数的注释冒号紧跟变量名,空一格后写注释,返回值注释->前后均空一格,当给有注释的赋默认值时应在等于前后加空格
Yes:
def munge(input: AnyStr): ...
def munge() -> AnyStr: ...
No:
def munge(input:AnyStr = None): ...
def munge()->PosInt: ...
#混合声明一般不被允许,while,if除外
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()