python代码优化

写 python 可以随心所欲,被 c , c++, java 折磨过几个世纪的痛苦瞬间释放,但 python 表示“请用PEP 8”。

PEP 8代码规范:https://www.python.org/dev/peps/pep-0008/

8 号 Python 增强提案又叫 PEP 8 ,它是针对 Python 代码格式而编订的风格指南,规定了最佳代码风格指南,统一的规则有利于易读,协作。以下是对重要规则的部分提取,全部内容请参考上述链接。

空格

  • 使用空格代替缩进,不要用tab
  • 每层缩进用 4 个空格
  • 每行字符数不超过 79
  • 多行表达式,首行 4 个空格,各行 8 个空格
  • 函数与类用两个空行隔开
  • 类中各方法用空行隔开
  • 赋值等号要用空格 a = "bcde"

缩进演示:

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# Add 4 spaces (an extra level of indentation) to distinguish arguments 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)

代码拆分多行:

条件语句 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()

list与函数多参数:

my_list = [
    1, 2, 3,
    4, 5, 6,
    ]
result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
    )

代码分行:

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

操作符多行:

# easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)
2 Likes
关闭