您的位置:首页 > 编程语言 > Python开发

python代码风格指南:PEP8 中文

2016-02-23 13:02 633 查看


摘要

本文给出主Python版本标准库的编码约定。CPython的C代码风格参见​PEP7。

本文和​PEP 257 文档字符串标准改编自Guido最初的《Python Style Guide》, 并增加了Barry的​GNU Mailman Coding Style Guide的部分内容。

本文会随着语言改变等而改变。 许多项目都有自己的编码风格指南,冲突时自己的指南为准。


一致性考虑

Guido的关键点之一是:代码更多是用来读而不是写。本指南旨在改善Python代码的可读性,即PEP 20所说的“可读性计数"(Readability counts)。

风格指南强调一致性。项目、模块或函数保持一致都很重要。

最重要的是知道何时不一致, 有时风格指南并不适用。当有疑惑时运用你的最佳判断,参考其他例子并多问!

特别注意:不要因为遵守本PEP而破坏向后兼容性!

部分可以违背指南情况:

遵循指南会降低可读性。

与周围其他代码不一致。

代码在引入指南完成,暂时没有理由修改。

旧版本兼容。


代码布局


缩进

每级缩进用4个空格。

括号中使用垂直隐式缩进或使用悬挂缩进。后者应该注意第一行要没有参数,后续行要有缩进。

Yes

# 对准左括号
foo = long_function_name(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)

No
# 不使用垂直对齐时,第一行不能有参数。
foo = long_function_name(var_one, var_two,
var_three, var_four)

# 参数的缩进和后续内容缩进不能区别。
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)


4个空格的规则是对续行可选的。

# 悬挂缩进不一定是4个空格
foo = long_function_name(
var_one, var_two,
var_three, var_four)if
语句跨行时,两个字符关键字(比如if)加上一个空格,再加上左括号构成了很好的缩进。

后续行暂时没有规定,至少有如下三种格式,建议使用第3种

# 没有额外缩进,不是很好看,个人不推荐.
if (this_is_one_thing and
that_is_another_thing):
do_something()

# 添加注释
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can frobnicate.
do_something()

# 额外添加缩进,推荐。
# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
and that_is_another_thing):
do_something()右边括号也可以另起一行。有两种格式,建议第2种。

# 右括号不回退,个人不推荐
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',
)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 代码风格