Python 代码风格指南 PEP8 摘要

一、代码布局

缩进

每层缩进使用 4 个空格

断行风格

  1. 断行首字母与括号开启符垂直对齐
# 这是正确的例子:
foo = long_function_name(var_one, var_two,
                         var_three, var_four)
  1. 悬挂缩进,首行不能有参数; 后面还有其它代码部分时,断行要添加一层缩进,使其与其它代码部分能区别开来
# 这是正确的例子,额外添加了一层缩进:
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)
# 这是错误的例子,悬挂缩进,后面还有其它代码时,需要添加一层额外的缩进加以区别:
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)
# 这是错误的例子,悬挂方式首行不能有参数:
foo = long_function_name(var_one, var_two,
    var_three, var_four)

if 条件断行

if ( 刚好有 4 个字条,相当于一层缩进。

对于 if 条件断行,以下几种风格都可以:

  1. 没有额外的缩进
if (this_is_one_thing and
    that_is_another_thing):
    do_something()
  1. 添加注释加以区分
# 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()
  1. 添加额外的缩进加以区分
# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
        and that_is_another_thing):
    do_something()

多行的括号

  1. 括号结束符与最后行的首字符对齐,如:
my_list = [
    1, 2, 3,
    4, 5, 6,
    ]

result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
    )
  1. 括号结束符与首行的首字符对齐, 如:
my_list = [
    1, 2, 3,
    4, 5, 6,
]
result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
)

Tab 符还是空格

用空格

每行最长长度

  1. 所有行都不超过 80 个字符:

    • 限制编辑器窗口的宽度,使能并排同时打开多个文件。
    • 设置编辑器宽度( set width to 80),来避免 wrapping
  2. 对于较少结构限制的长文本(如 docstring 或注释),行长应限制为 72 个字符。

  3. 如果团队成员都同意使用长行,则可以将行长增加到不超过 100 个字符,但是 docstring 和注释还必须为 72 个字符。

  4. 有括号的长行可以用 implicit continuation 来断行,其它的可以用 \ 来断行,如:

with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

操作符要和操作数在一起

# 推荐的正确的风格,这样很容易将操作符与操作数匹配:
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)
# 这种风格现成已不推荐使用了:
income = (gross_wages +
          taxable_interest +
          (dividends - qualified_dividends) -
          ira_deduction -
          st
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值