Python代码规范

 

目录

代码布局--换行

缩进

行限制

代码布局--空行

代码布局--导入

空格的使用

不使用空格

其它规范

注释--文档字符串

其它建议

结尾加逗号

其它

 


代码布局--换行

缩进

参数太多、定义函数时换行

# 与开头分隔符对齐
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# 悬挂缩进
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)

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',
)

行限制

# 在括号内换行(例如上一部分)
# 反斜线换行
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)

代码布局--空行

class OnePerson(object):
    def name(self):
        pass

    def weight(self):
        pass


def my_name():
    pass


def my_height():
    pass

代码布局--导入

# 导入每个库都应单独起一行
import os
import sys

# 相同来源可以在同一行
from subprocess import Popen, PIPE
# 绝对导入
import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example

# 相对导入
from . import sibling
from .sibling import example
# 模块中包含类,从模块中导入类
from myclass import MyClass
from foo.bar.yourclass import YourClass

# 导入模型,使用时用myclass.MyClass和foo.bar.yourclass.YourClass
import myclass
import foo.bar.yourclass
# 带有两个前导下划线和两个尾随下划线的名称放在文档字符串之后,其它代码之前
from __future__ import barry_as_FLUFL

__all__ = ['a', 'b', 'c']
__version__ = '0.1'
__author__ = 'Cardinal Biggles'

import os
import sys

空格的使用

不使用空格

# 以下情况不要空格:
# 紧挨着括号
# 逗号和括号之间
# 在逗号、分号或冒号之前
# 紧跟在函数名后面调用参数
# 在开始索引或切片的左括号前
spam(ham[1], {eggs: 2})
foo = (0,)
if x == 4: print x, y; x, y = y, x
spam(1)
dct['key'] = lst[index]
# 没必要刻意保持运算符对齐
x = 1
y = 2
long_variable = 3
# 冒号在切片时,两边的空格数量保持相同
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]

其它规范

# 二进制运算符的两边各一个空格
# 最低优先级的符号两侧各一个空格
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)
# 函数注释:有冒号按冒号规则,有箭头->两边各一个空格
def munge(input: AnyStr): ...
def munge() -> PosInt: ...
# 当用于指示函数参数的默认值时,不要在=周围使用空格
def complex(real, imag=0.0):
    return magic(r=real, i=imag)
# 但是,在将参数注释与默认值组合时,请在=周围使用空格
def munge(sep: AnyStr = None): ...
def munge(input: AnyStr, sep: AnyStr = None, limit=1000): ...
# 最好不要用复合语句(一行多条语句)
if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()

注释--文档字符串

# 多行文档字符串,最后的引号单起一行
"""Return a foobang

Optional plotz says to frobnicate the bizbaz first.
"""
# 单行文档字符串,引号都在同一行
"""Return an ex-parrot."""

其它建议

结尾加逗号

# 一个元素的元组必须有逗号,其它时候都是可选的
FILES = ('setup.cfg',)

# 当值、参数或导入项的列表预计会随着时间的推移而扩展时,结尾加逗号有用,每个元素一行,且结尾加逗号
FILES = [
    'setup.cfg',
    'tox.ini',
    ]
initialize(FILES,
           error=True,
           )

其它

# 用is not ,而不是not ...is
if foo is not None:
# 给函数命名,用def,而不是lambda
# Correct:
def f(x): return 2*x
# Wrong:
f = lambda x: 2*x
# 函数的return应保持一致性
def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0:
        return None
    return math.sqrt(x)
# 用''.startswith()和''.endswith()检查字符串的前缀和后缀,而不是切片
# Correct:
if foo.startswith('bar'):
# Wrong:
if foo[:3] == 'bar':
# 比较对象的类型用isinstance()而不是type()
# Correct:
if isinstance(obj, int):
# Wrong:
if type(obj) is type(1):
# 不要用==来比较布尔值与True/False
# Correct:
if greeting:
# Wrong:
if greeting == True:
# 变量的注释,冒号后空一格,如果有赋值,=两侧各一个空格
code: int

class Point:
    coords: Tuple[int, int]
    label: str = '<unknown>'

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值