PEP 8 -- Python代码风格指南

介绍

    这篇文档给出了在主要的Python发行版中标准库代码的编码风格。这篇文档和PEP 257主要来自于对Guido的Python代码风格指南论文的改动以及增长了一些Barry的风格指南的内容。python

    许多项目都有它们本身的编码风格指南。当发生编码风格冲突的时候,特定项目的编码风格指南优先于这里的风格指南。ide

Code lay-out

缩进

    每一个缩进层级使用4个空格。ui

 连续行应当被正确的排列,或者用Python中精确的行垂直的来排列括弧里面的元素,或者使用悬挂式缩进的来排列。当悬挂式缩进的方式被采用时,下面的状况应当被考虑。在第一行中应该没有参数,而且后续的缩进应当清楚的将本身标记为一个连续行。this

#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表达式的关系。看看下面的状况。spa

# 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”为缩进方式的状况。rest

  Python3不容许混合“Tab”和空格做为缩进方式。code

  Python2中代码缩进混合了“Tab”和空格的,“Tab”将会被转化成空格。当使用-t参数调用python2命令行解析器,解析器将会报出代码在缩进的过程当中非法混合了“Tab”和空格的警告。当使用-tt,这些警告将会变成错误。这些参数被极力推荐。three

 

tomorrow will be better , 有空再慢慢补充。

 

 

 

【参考连接】

https://www.python.org/dev/peps/pep-0008/#indentation

相关文章
相关标签/搜索