介绍
这篇文档给出了在主要的Python发行版中标准库代码的编码风格。这篇文档和PEP 257主要来自于对Guido的Python代码风格指南论文的改动以及增加了一些Barry的风格指南的内容。
许多项目都有它们自己的编码风格指南。当发生编码风格冲突的时候,特定项目的编码风格指南优先于这里的风格指南。
Code lay-out
缩进
每个缩进层级使用4个空格。
连续行应当被正确的排列,或者用Python中精确的行垂直的来排列括弧里面的元素,或者使用悬挂式缩进的来排列。当悬挂式缩进的方式被采用时,下面的情况应当被考虑。在第一行中应该没有参数,并且后续的缩进应当清楚的将自己标记为一个连续行。
#yes
# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)
#More indentaion 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)
对于连续行而言,four-space规则是可选的。
当if表达式的条件部分足够长,被要求写到多行中去。可以这样去做if后面接一个空格,接一个括号,下面的连续行采用四个空格缩进的方式。这样可以很显式的去表明if表达式的关系。看看下面的情况。
# 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',
)
Tabs or Spaces
空格是Python中推荐的缩进方法。Tab有时候也会用到,但仅仅是为了去对付原有代码以“Tab”为缩进方式的情况。
Python3不允许混合“Tab”和空格作为缩进方式。
Python2中代码缩进混合了“Tab”和空格的,“Tab”将会被转化成空格。当使用-t参数调用python2命令行解析器,解析器将会报出代码在缩进的过程中非法混合了“Tab”和空格的警告。当使用-tt,这些警告将会变成错误。这些参数被极力推荐。
tomorrow will be better , 有空再慢慢补充。
【参考链接】
https://www.python.org/dev/peps/pep-0008/#indentation