002.[python学习]python编码规范pep8学习——PEP8第一部分代码布局

时间:2023-03-09 07:39:49
002.[python学习]python编码规范pep8学习——PEP8第一部分代码布局

关于PEP8的详细说明可以参考官方原文:http://legacy.python.org/dev/peps/pep-0008/

我参考官方文档及其他文章,摘出相关内容而得此文章,具体参考其他文章见文中最后参考资料处。

当想要让自己所写的代码为更多人使用、交流学习时,不能写出只有机器认识的代码,而是对于人而言具有良好的可读性,此时就需要遵从一个公共的约束来规范自己的代码,那么《Style Guide for Python Code(PEP8)》是个很好的选择。

首先PEP8中声明,有以下有理由忽略特定的规范:

使用规范会降低代码可读性可不遵守;

为了与其他代码保持一致可以不遵守规范(这种情况也许是历史原因);

因为代码早于引进规范并且没有必要理由去修改代码时,可以不遵守规范;

代码需要兼容不支持代码风格建议的旧版本python时可不遵守。

1 代码布局

1.1    缩进

每个缩进使用4个空格。

python是靠缩进区分语句块的,语句块缩进不正确是无法通过语法检查的,这种是必须遵守的;

跨行的语句需要遵守下面规范(英语不行,暂时就不翻译了,意会下):

Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent [7]. When using a hanging indent the following should be considered; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line.

指的是续行应该和括起来的内容垂直对齐,或者使用叫hanging indent的格式。

下面是符合规范的例子:

 # 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)
# Hanging indents *may* be indented to other than 4 spaces.
foo = long_function_name(
var_one, var_two,
var_three, var_four)
# No extra indentation.
if (this_is_one_thing and
that_is_another_thing):
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() # Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
and that_is_another_thing):
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',
)

下面是不符合规范的例子:

 # 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)

1.2     使用tab还是空格

空格是更好的选择,尽量不要空格和tab混用。Python3中不允许混用的方式,python2中可以使用-t或-tt参数进行检查,混用时前者会产生警告,后者会产生错误。

1.3    单行最大长度79个字符

1.4    空白行:*函数和类定义之间使用两个空白行,类中函数定义之间使用单个空白行。

1.5    源文件编码格式:官方说python3用UTF-8,python2用ASCII,我觉得最好都用UTF-8。

1.6    模块导入应该单号导入一个,除from xxx import a, b这种外;导入语句应该放在源文件最前面,紧跟着模块注释和文档描述之后,在模块全局变量和常量之前。模块应按照顺序导入:最先导入系统标准模块,再导入相关第三方模块,最后导入本地自己编写的模块。