Google开源项目编码规范——python篇 - littleboy12580/learning_python GitHub Wiki
绝对不要用tab, 也不要tab和空格混用. 对于行连接的情况, 你应该要么垂直对齐换行的元素, 或者使用4空格的悬挂式缩进(这时第一行不应该有参数)
# Aligned with opening delimiter
foo = long_function_name(var_one, var_two,
var_three, var_four)
# Aligned with opening delimiter in a dictionary
foo = {
long_dictionary_key: value1 +
value2,
...
}
# 4-space hanging indent; nothing on first line
foo = long_function_name(
var_one, var_two, var_three,
var_four)
# 4-space hanging indent in a dictionary
foo = {
long_dictionary_key:
long_dictionary_value,
...
}
顶级定义比如函数或者类定义,需要空两行;方法定义, 类定义与第一个方法之间, 都应该空一行。
- 括号内不要有空格
- 不要在逗号, 分号, 冒号前面加空格, 但应该在它们后面加(除了在行尾)
- 参数列表, 索引或切片的左括号前不应加空格
- 在二元操作符两边都加上一个空格, 比如赋值(=), 比较(==, <, >, !=, <>, <=, >=, in, not in, is, is not), 布尔(and, or, not)
- 当’=’用于指示关键字参数或默认参数值时, 不要在其两侧使用空格
- 不要用空格来垂直对齐多行间的标记, 因为这会成为维护的负担(适用于:, #, =等)
如果一个类不继承自其它类, 就显式的从object继承. 嵌套类也一样
在文件和sockets结束时, 显式的关闭它;推荐使用with语句
with open("hello.txt") as hello_file:
for line in hello_file:
print line
对于不支持使用”with”语句的类似文件的对象,使用 contextlib.closing():
import contextlib
with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
for line in front_page:
print line
-
每个导入应该独占一行
-
导入总应该放在文件顶部, 位于模块注释和文档字符串之后, 模块全局变量和常量之前. 导入应该按照从最通用到最不通用的顺序分组:
- 标准库导入
- 第三方库导入
- 应用程序指定导入
-
每种分组中, 应该根据每个模块的完整包路径按字典序排序, 忽略大小写
module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_VAR_NAME, instance_var_name, function_parameter_name, local_var_name
- 单字符名称, 除了计数器和迭代器
- 包/模块名中的连字符(-)
- 双下划线开头并结尾的名称(Python保留, 例如__init__)
- 所谓”内部(Internal)”表示仅模块内可用, 或者, 在类内是保护或私有的
- 用单下划线(_)开头表示模块变量或函数是protected的(使用import * from时不会包含)
- 用双下划线(__)开头的实例变量或方法表示类内私有
- 将相关的类和顶级函数放在同一个模块里,没必要限制一个类一个模块
- 对类名使用大写字母开头的单词(如CapWords, 即Pascal风格), 但是模块名应该用小写加下划线的方式(如lower_with_under.py).
Type | Public | Internal |
---|---|---|
Modules | lower_with_under | _lower_with_under |
Packages | lower_with_under | |
Classes | CapWords | _CapWords |
Exceptions | CapWords | |
Functions | lower_with_under() | _lower_with_under() |
Global/Class Constants | CAPS_WITH_UNDER | _CAPS_WITH_UNDER |
Global/Class Variables | lower_with_under | _lower_with_under |
Instance Variables | lower_with_under | _lower_with_under (protected) or __lower_with_under (private) |
Method Names | lower_with_under() | _lower_with_under() (protected) or __lower_with_under() (private) |
Function/Method Parameters | lower_with_under | |
Local Variables | lower_with_under |