Python 代码风格养成记

2018-02-13  本文已影响0人  秦时明星

代码布局

#对准左括号
foo = (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',
    )
Yes:
import os
import sys
from subprocess import Popen, PIPE

No:
import sys, os

导⼊始终在⽂件的顶部,在模块注释和⽂档字符串之后,在模块全局变 量和常量之前。
导⼊顺序如下:标准库进⼝,相关的第三⽅库,本地库。各组的导⼊之间 要有空⾏。

# 括号⾥边避免空格

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

dct['key'] = lst[index]

# No

spam (1)

dct ['key'] = lst [index]
#Yes
x = 1

y = 2

long_variable = 3

# No
x = 1

y = 2

long_variable = 3
# 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

if foo == 'blah':

do_blah_thing()

do_one()

do_two()

do_three()

# No

if foo == 'blah': do_blah_thing()

do_one(); do_two(); do_three()
# No

if foo == 'blah': do_blah_thing()

for x in lst: total += x

while t < 10: t = delay()

更不是:

# No

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)
上一篇 下一篇

猜你喜欢

热点阅读