【Python技巧】Python代码格式规范

PEP 8 -- Style Guide for Python Code

  1. 每个缩进固定为四个空格(一个tab)注意全篇应统一使用tab或者是空格

  2. 控制最大字符,每行最多79字符。对于没有分割的过长的文本,应限制在每行72字符

  3. 每行名字过长时,格式为:

# (1)将第二行变量与第一行对齐
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# (2)如果第一行写不下,将函数中的变量换行
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)
  1. if语句过长时,格式为:
if (this_is_one_thing and
    that_is_another_thing):
    do_something()

# 另一种写法,如果and也换行,注意缩进
if (this_is_one_thing
        and that_is_another_thing):
    do_something()

5.列表的生成:

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

6.计算符号的位置:应该位于每行行首

income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

7.空行

Surround top-level function and class definitions with two blank lines.
顶层函数和类的定义前,加两行空格

Method definitions inside a class are surrounded by a single blank line.
在类内定义方法时,加一行空格

Use blank lines in functions, sparingly, to indicate logical sections.
在函数中使用空格来表示出逻辑

8.空格

(1) 括号后不要跟空格。

Yes: spam(ham[1], {eggs: 2})
No:  spam( ham[ 1 ], { eggs: 2 } )

(2)逗号和括号之间不要加空格

Yes: foo = (0,)
No:  bar = (0, )

(3)逗号后加空格,逗号前不加

Yes: if x == 4: print x, y; x, y = y, x
No:  if x == 4 : print x , y ; x , y = y , x

(4)冒号:数字与冒号之间不加,但如果是函数、其他运算符等有优先级关系的运算之间的冒号要加空格

ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
ham[lower:upper], ham[lower:upper:], ham[lower::step]
ham[lower+offset : upper+offset]
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
ham[lower + offset : upper + offset]
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Introduction This document gives coding conventions for t...
    wuutiing阅读 4,687评论 0 9
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 4,465评论 0 5
  • 原文 原文下载之后的格式略有点不友好,利用简述的markdown,编辑一下.版权归原作者 PEP Index > ...
    大飞哥阅读 2,547评论 0 0
  • --< > 令人讨厌的小人物身上有着愚蠢的一致性 --(A Foolish Consistency is the ...
    LittleWizard阅读 3,275评论 0 4
  • 夜晚微薄的雾气在路灯的折射下形成一个一个奇怪的光圈,我想在此刻,远方有一个号角打破这片死一样的沉寂。只可惜我...
    素水流年那一年阅读 361评论 0 0