如果一个文本字符串在一行放不下, 可以使用圆括号来实现隐式行连接:
x = ('这是一个非常长非常长非常长非常长 ’
‘非常长非常长非常长非常长非常长非常长的字符串’)
在注释中,如果必要,将长的URL放在一行上。
Yes: # See details at
http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html
No: # See details at
http://www.example.com/us/developer/documentation/api/content/\
v2.0/csv_file_name_extension_full_specification.html
注意上面例子中的元素缩进; 你可以在本文的 :ref:`缩进 `部分找到解释.
括号
–
宁缺毋滥的使用括号
除非是用于实现行连接, 否则不要在返回语句或条件语句中使用括号. 不过在元组两边使用括号是可以的.
Yes: if foo:
bar()
while x:
x = bar()
if x and y:
bar()
if not x:
bar()
return foo
for (x, y) in dict.items(): …
No: if (x):
bar()
if not(x):
bar()
return (foo)
缩进
–
用4个空格来缩进代码
绝对不要用tab, 也不要tab和空格混用. 对于行连接的情况, 你应该要么垂直对齐换行的元素(见 :ref:`行长度 <line_length>` 部分的示例), 或者使用4空格的悬挂式缩进(这时第一行不应该有参数):
Yes: # 与起始变量对齐
foo = long_function_name(var_one, var_two,
var_three, var_four)
字典中与起始值对齐
foo = {
long_dictionary_key: value1 +
value2,
…
}
4 个空格缩进,第一行不需要
foo = long_function_name(
var_one, var_two, var_three,
var_four)
字典中 4 个空格缩进
foo = {
long_dictionary_key:
long_dictionary_value,
…
}
No: # 第一行有空格是禁止的
foo = long_function_name(var_one, var_two,
var_three, var_four)
2 个空格是禁止的
foo = long_function_name(
var_one, var_two, var_three,
var_four)
字典中没有处理缩进
foo = {
long_dictionary_key:
long_dictionary_value,
…
}
空行
–
顶级定义之间空两行, 方法定义之间空一行
顶级定义之间空两行, 比如函数或者类定义. 方法定义, 类定义与第一个方法之间, 都应该空一行. 函数或方法中, 某些地方要是你觉得合适, 就空一行.
空格
–
按照标准的排版规范来使用标点两边的空格
括号内不要有空格.
按照标准的排版规范来使用标点两边的空格
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: spam(1)
no: spam (1)
Yes: dict[‘key’] = list[index]
No: dict [‘key’] = list [index]
在二元操作符两边都加上一个空格, 比如赋值(=), 比较(==, <, >, !=, <>, <=, >=, in, not in, is, is not), 布尔(and, or, not). 至于算术操作符两边的空格该如何使用, 需要你自己好好判断. 不过两侧务必要保持一致.
Yes: x == 1
No: x<1
当’='用于指示关键字参数或默认参数值时, 不要在其两侧使用空格.
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:
foo = 1000 # 注释
long_name = 2 # 注释不需要对齐
dictionary = {
“foo”: 1,
“long_name”: 2,