Python 风格规范(Google)
本项目并非 Google 官方项目, 而是由国内程序员凭热情创建和维护。
如果你关注的是 Google 官方英文版, 请移步 Google Style Guide
以下代码中 Yes 表示推荐,No 表示不推荐。
不要在行尾加分号, 也不要用分号将两条命令放在同一行。
每行不超过80个字符
以下情况除外:
不要使用反斜杠连接行。
Python会将 圆括号, 中括号和花括号中的行隐式的连接起来 , 你可以利用这个特点. 如果需要, 你可以在表达式外围增加一对额外的圆括号。
推荐:
foo_bar(self, width, height, color='black', design=None, x='foo', emphasis=None, highlight=0) if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong'):
如果一个文本字符串在一行放不下, 可以使用圆括号来实现隐式行连接:
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:`缩进 <indentation>`部分找到解释.
宁缺毋滥的使用括号
除非是用于实现行连接, 否则不要在返回语句或条件语句中使用括号. 不过在元组两边使用括号是可以的.
Yes:
if foo: bar()while x: x = bar()if x and y: bar()if not x: bar()return foofor (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, ... }
新闻热点
疑难解答