Python - 部分PEP8规范

写代码就像写字一样,为什么有的人写的字十分漂亮,而有的人写的字过后连自己都不认识,最主要还是从一开始是否对自己严格要求。从现在开始就当自己是个初学者,把代码写漂亮点。以下截取了部分PEP8代码规范,里面掺杂了一些个人中文注解。
想看英文原版,就点击 https://legacy.python.org/dev/peps/pep-0008/
想看中文翻译版,就点击 https://blog.csdn.net/ratsniper/article/details/78954852

缩进


# 函数参数应垂直对齐

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:                        
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

No:    
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)

Yes:
以下三种都行   
if条件换行不增加额外的空格

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条件换行增加额外的空格

if (this_is_one_thing
        and that_is_another_thing):
    do_something()

Yes:
以下四种都行
对于闭括号,可以跟参数保持对齐,像前两种;也可以跟变量保持对齐,像后两种

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个字符内,较长的代码行选择在小括号,中括号以及大括号中的隐式续行方式。这种方式应该优先使用,而不是使用反斜杠续行。
# 但反斜杠有时依然很有用。比如,比较长的,多个with状态语句,不能使用隐式续行,所以反斜杠是可以接受的   

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

# 运算符应该在换行的前面   
Yes:    

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

No:

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

空行

         
# 顶层的类或函数用两个空行隔开,类里面的方法用一个空行隔开,以下为示例

class xxx(object):
        pass


class yyy(object):
    """
    comment
    """
    def a(self): # comment
        """ comment """
        pass

    def c(self): # comment
        """ comment """
        pass       

导入

   
# 不要一行导入多个模块
Yes:

import os
import sys

No: 

import sys, os  

 
# 但是可以这样   

from subprocess import Popen, PIPE    


导入总是位于文件的顶部,在模块注释和文档字符串之后,在模块的全局变量与常量之前。
导入应该按照以下顺序分组:
标准库导入
相关第三方库导入
本地应用/库特定导入
你应该在每一组导入之间加入空行  
    
导入尽量使用绝对路径

import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example  


显示的指定相对导入路径是使用绝对路径的一个可接受的替代方案,特别是在处理使用绝对路径导入不必要冗长的复杂包布局时   

from . import sibling  #加载当前目录下的sibling.py文件
from .sibling import example  #加载当前目录下sibling.py的example    

双下划线的变量应出现在导入前,但除了from __future__ imports

"""This is the example module.

This module does stuff.
"""

from __future__ import barry_as_FLUFL

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

import os
import sys

引号


在Python中,单引号和双引号字符串是相同的。PEP不会为这个给出建议。选择一条规则并坚持使用下去。当一个字符串中包含单引号或者双引号字符的时候,使用和最外层不同的符号来避免使用反斜杠,从而提高可读性。
对于三引号字符串,总是使用双引号字符来与PEP 257中的文档字符串约定保持一致。

空格


紧跟括号不要有空格
Yes: spam(ham[1], {eggs: 2})
No:  spam( ham[ 1 ], { eggs: 2 } )

逗号冒号分号前不要有空格
Yes: if x == 4: print x, y; x, y = y, x
No:  if x == 4 : print x , y ; x , y = y , x

冒号在切片中就像二元运算符,在两边应该有相同数量的空格(把它当做优先级最低的操作符)。在扩展的切片操作中,所有的冒号必须有相同的间距。例外情况:当一个切片参数被省略时,空格就被省略了。
Yes:
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]

No:
ham[lower + offset:upper + offset]
ham[1: 9], ham[1 :9], ham[1:9 :3]
ham[lower : : upper]
ham[ : upper]

紧贴在函数参数的左括号之前
Yes: spam(1)
No:  spam (1)

紧贴索引或者切片的左括号之前
Yes: dct['key'] = lst[index]
No:  dct ['key'] = lst [index]

变量赋值,左右各一个等号
Yes:
x = 1
y = 2
long_variable = 3

No:
x             = 1
y             = 2
long_variable = 3

避免在尾部添加空格。因为尾部的空格通常都看不见,会产生混乱:比如,一个反斜杠后面跟一个空格的换行符,不算续行标记
总是在二元运算符两边加一个空格:赋值(=),增量赋值(+=,-=),比较(==,<,>,!=,<>,<=,>=,in,not,in,is,is not),布尔(and, or, not)
如果使用具有不同优先级的运算符,请考虑在具有最低优先级的运算符周围添加空格

Yes:

i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

No:

i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)

在关键字参数或者默认参数值的时候,不要在=附近加上空格。
Yes:

def complex(real, imag=0.0):
    return magic(r=real, i=imag)

No:

def complex(real, imag = 0.0):
    return magic(r = real, i = imag)

一行一句 


Yes:

if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()

No:

if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()

注释


注释开头的单词首字母大写,一般使用#加一个空格开头
行内注释一般与代码隔开两个空格

命名规范


模块应该用简短全小写的名字,如果为了提升可读性,下划线也是可以用的。Python包名也应该使用简短全小写的名字,但不建议用下划线。
类名应该用首字母大写的名字
异常名,因为异常一般都是类,所有类的命名方法在这里也适用。然而,你需要在异常名后面加上“Error”后缀
函数名应该小写,如果想提高可读性可以用下划线分隔
普通变量全小写和_,常量用全大写和_

函数和方法参数
始终要将self作为实例方法的的第一个参数。
始终要将cls作为类静态方法的第一个参数。
如果函数的参数名和已有的关键词冲突,在最后加单一下划线比缩写或随意拼写更好。因此class_比clss更好。

猜你喜欢

转载自www.cnblogs.com/ddzj01/p/10930715.html