比较好的作法以下:python
对准开始的分隔符:ide
# 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)
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)
对于续行来讲,四个空格的缩进是可选的。this
可选的以下:编码
# Hanging indents *may* be indented to other than 4 spaces.悬挂缩进的时候能够不是四个空格 foo = long_function_name( var_one, var_two, var_three, var_four)
当使用if语句的时候,若是条件刚好的缩进为四个空格空格,那么致使后面的语句的缩进也是四个空格,那么这种状况下是能够接受的,以下所示:spa
没有额外的缩进:设计
# No extra indentation. if (this_is_one_thing and that_is_another_thing): do_something()
添加一个注释来进行分割缩进,作到语法高亮显示: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()
在续行中添加额外的缩进:
# 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()
成对的小括号,中括号在多行的结构中能够写成多行,而后括号在第一个不为空白的位置结束。以下:
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', )
关于tab的空格的选择,在python2中是能够混用的,可是在python3中,只能用一种风格。
行的最大长度为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)
Top level函数和类的定义的时候,空两行。
类中方法的定义空一行。
在函数中谨慎使用空行来表示相关的逻辑段。
无关的函数之间用一个空行进行分割。
在源文件中一直使用utf-8编码,在python2中使用ascll编码。
文件,在python2 中使用ascll编码,在python3中使用utf-8编码
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”。
E:在导入模块的时候,应该避免通配符的存在,以下:
from <module> import *
在对于字符串的标示中,使用双引号仍是单引号是没有区别的,主要就是二者混合使用从而避免反斜杠的出现。
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
A. 避免在任何结尾添加空白。
B. 在下列操做符中左右各留空白
assignment ( = ),
augmented assignment ( += , -= etc.),
comparisons ( == , < , > , != , <> , <= , >= , in , not in , is , is not ), Booleans ( and , or , not )
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)
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()
在修改的代码的时候,务必修改注释。
注释必须是英文,最好是完整的句子,首字母大写
在一段代码前增长注释,在#后添加一个空格,段落之间只有一个#做为行间隔
# Description : Module config. # # Input : None # # Output : None
在使用行注释的时候,在代码句子结束以后至少两个空格,而后用#开头后跟一个空格
x = x + 1 # Increment x But sometimes, this is useful: x = x + 1 # Compensate for border
在上面例子中,表示不要使用无效注释,主要是说明其目的
在全部的公共模块,函数,类,方法中加入文档注释,这些注释写在def以后。
在进行多行注释的时候,注意“”“结束的时候,必须独占一行,以下:
"""Return a foobang Optional plotz says to frobnicate the bizbaz first. """ xxxxxxxxxx
当文档注释是一行的时候,确保开始的““”和“”“在同一行中。
使用单独的小写字母(b)
使用单独的大写字母(B)
使用小写字母(lowercase)
使用小写字母和下划线(lower_case_with_underscores)
使用大写字母(UPPERCASE)
使用大写字母和下划线(UPPER_CASE_WITH_UPPERCASE)
驼峰式写法(CamelCase):在使用缩写的时候,大写优于小写例如HTTPServer优于HttpServer
首字母大写,而后使用下划线是一种丑陋的写法
在写变量的时候,尽可能避免小写的l和大写字母O和大写字母I,主要缘由是容易和数字中1,0相混淆
模块尽可能使用简短的所有小写的名称,若是能够增长可读性那么可使用下划线,python的包不推荐使用下划线,可是在引用其余语言写的扩展包中可使用下划线来表示区分
类名称主要遵循为CapWords约定,表示为首字母大写
异常归于类,从而也要遵循类名的规范,主要是在后缀上必须添加“Error“
全局变量只在模块类有效,和function命名相同
方法名称所有为小写,下划线是可选的(在增长可读性的基础上使用)
类的方法第一个参数老是self
类方法的静态变量老是为cls
若是一个方法的参数和保留字相冲突,那么在后面添加下划线进行区分
常量命名所有使用大写,可使用下划线进行分割
单独比较的时候使用is或者is not,不要使用==进行比较。
当实现比较的方法的时候,最好所有实现
eq , ne ,lt , le , gt , ge ),而不要单独实现一个。
使用startswith() and endswith()代替切片进行序列前缀或后缀的检查。好比
Yes: if foo.startswith(‘bar’):优于
No: if foo[:3] == ‘bar’: