数据蛙数据分析基础学习数据蛙就业班

Python - PEP-8 编写规范总结

2020-04-13  本文已影响0人  Gaafung峰

缩进

缩进使用4个空格符,利用Tab

函数

设定4个参数

var_one = '1'
var_two = '2'
var_three = '3'
var_four = '4'

正确格式

# 假设函数参数
def long_name(var_one, var_two,
              var_three, var_four):
    print(var_one + var_two + var_three + var_four)
# 函数参数过多需要换行,则放在“(”后


long_name(var_one, var_two,
          var_three, var_four)
# 同理
long_name(
    var_one, var_two,
    var_three, var_four)
# 当以'('为末尾进行换行,下一行保持前面有4个空格的缩进即可

错误格式

def long_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)
# 函数变量以'('为末尾换行时,下一行还是需要对齐(,目前变量缩进是错误

long_name(var_one, var_two,
    var_three, var_four)
# 不应该直接换行后4个缩进,要对齐(

if

可以接受以下写法:

# 无额外缩进,且对齐美观
if (this_is_one_thing and
    that_is_another_thing):
    do_something()


# 在条件延续行上添加一些额外的缩进
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',
)

行长

限制所有行最多79个字符。
如果超过,请换行处理
错误

one_thing = 1
two_thing = 2
three_thing = 3
four_thing = 4
if one_thing + two_thing == three_thing and one_thing + three_thing == four_thing and one_thing + four_thing != two_thing or one_thing > 0:
    print('you are right')

正确

if one_thing + two_thing == three_thing and one_thing + three_thing == four_thing \
        and one_thing + four_thing != two_thing or one_thing > 0:
    print('you are right')

或者另外例子

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

正确写法让代码增加可读性,且遵循数学传统

import的正确写法

错误

import os, sys

正确

import os
import sys

from subprocess import Popen, PIPE

摆放的位置总是在文件的顶部,紧随任何模块注释和文档字符串之后,以及模块全局变量和常量之前。

导入模块顺序,应遵循如下:
1、标准库导入
2、相关第三方进口
3、本地应用程序/特定于库的导入

针对不同类型导入模块,应空一行处理。

上一篇下一篇

猜你喜欢

热点阅读