Python编码规范
1 排版
1.1 Indentation缩进
在参数过多时适当缩进
foo = long_function_name(var_one, var_two,
var_three, var_four)
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
换行应该使用同级的缩进
Yes:
foo = long_function_name(
var_one, var_two,
var_three, var_four)
No:
foo = long_function_name(var_one, var_two,
var_three, var_four)
Yes:
if (this_is_one_thing and
that_is_another_thing):
do_something()
注释需要具有相同的缩进
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can frobnicate.
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',
)
1.2 最大行长
所有行最大长度被限制在79个字符
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())
过长需要续行使用’\’二元操作符的位置
No: 操作符里操作数过远
income = (gross_wages +
taxable_interest +
(dividends - qualified_dividends) -
ira_deduction -
student_loan_interest)
Yes: 正确的方式可以更容易的去匹配操作符与操作数
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)
1.3空行
顶层函数和类定义:前后两行空白
类方法定义:前后一行空白
应该添加额外空行来曲分不同组的函数
在函数定义内部使用空行来分隔不同的逻辑片段
源文件编码:
Python2使用ASCII编码或者Python3使用UTF-8编码,不应该声明编码类型。
所以在使用Python2时,我们应该在源文件开始声明编码类型。
#coding=utf-8
1.4 Import引入
引入模块应该分行
Yes:
import os
import sys
No:
import sys, os
It's okay to say this though:
from subprocess import Popen, PIPE
引入声明应该总是在文件顶部,仅在任何模块的注释和文档字符后面,同时也要处在全局变量和常量声明之前。
引入应该按照下面的顺序分组并书写
标准库
相关第三方库
本地 应用/库 特殊量的引入
你应该用空行隔开每个分组
• 在用户包/或者可引用的文件夹外的文档内import 模块应该使用绝对引用的方式
import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example
• 在用户包内import 模块应该使用相对引用的方式,确保包内路径的可靠性
from . import sibling
从当前目录下引用