python PEP8相关介绍

  在学习了python相关技术之后,开始重视其开发规范,以满足代码的可读性以及可维护性。主要的是学习了PEP8-style for python code的相关内容。

  1.  代码布局
    •  缩进:每一级4个缩进。连续跨行应该使用圆括号或大括号或者使用悬挂缩进。
# 定界符(圆括号或大括号)
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)

# 悬挂缩进也应增加一个等级
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)

#注意:4空格在连续换行中为可选项
# 悬挂缩进中可以不适用4空格一级的规则。
foo = long_function_name(
  var_one, var_two,
  var_three, var_four)
#首尾不写参数
my_list = [ 1, 2, 3, 4, 5, 6, ] result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f', )
    •  Tab还是空格:python2中可以混合使用,python3强制只允许一种。
    • 最大长度:79个字符,docstrings/comments则应少于 72字符,用"/"连接两行:
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)
    • 空行:用两个空行包裹顶级函数或类,类中的方法定义被一个空白行包围。函数间尽量少的使用空白行(如果是一组逻辑则省略),函数内的逻辑也应尽可能少的使用空白行,除非为了显示更有逻辑性
    • python3源文件修改应为UTF-8编码,定义标准库必须使用ASCII且内容必须使用英文
    • 单独import必须分两行,from import可以在一行中引入,IMPORT必须在文件头使用,在module comment 和docstrings之后,在模块全局变量或实例之前
 #Yes: 
import os
import sys
#No:  
import sys, os
#YES
from subprocess import Popen, PIPE
'''模块的引入顺序应该为:
  1 标准库
  2 第三方库
  3 本地应用或库
在每个类别之间应该添加空白行'''
    • 提倡绝对导入,但如果绝对导入比较冗长可相对导入,python3中不鼓励,会出现未知bug
import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example

#相对导入
from . import sibling
from .sibling import example
    • 通配符导入from <module> import *应尽可能避免
    • 模块级命名应该在docstring之后,任何声明之前(__future__除外)
"""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
    • 单双引号没有强制规定,但整个程序应该只使用一种规则,在docstring中应该使用三个双引号“”“
  •  表达式和语句中的空格
    • 以下几种情况不要使用空格
      • #括号紧跟的前后
        Yes: spam(ham[1], {eggs: 2})
        No:  spam( ham[ 1 ], { eggs: 2 } )
        #逗号加反括号
        Yes: foo = (0,) No: bar = (0, )
        #逗号,分号,冒号前
        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
        
        #这些运算符左右各加一个空格:assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (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:

        def munge(input: AnyStr): ...
        def munge() -> AnyStr: ...
        

        No:

        def munge(input:AnyStr = None): ...
        def munge()->PosInt: ...
        
        #混合声明一般不被允许,while,if除外

        Yes:

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

        Rather not:

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





    • 什么时候使用,)
      • #便于版本控制
            Yes:
        
            FILES = [
                'setup.cfg',
                'tox.ini',
                ]
            initialize(FILES,
                       error=True,
                       )
        
            No:
        
            FILES = ['setup.cfg', 'tox.ini',]
            initialize(FILES, error=True,)
        #除了单元素元组是强制的以外,其他的都是为了更好的可读性
        
    • 注释
      •  鼓励使用多行注释,如果是单行,首字母应该大写(中文应该没有这个问题,而且变量的小写在首字母时应保持小写性质)
      •  单行注释无需句号,在使用句号后应该用两个空格隔开
    • 注释块(block comments):#后加空格
    • 注释行(line comments):跟程序至少间隔2个空格,且应该#加一个空格开始
    • 文档描述:
      • 应包括:公共模块,函数,类以及方法,不应该包括私有模块,但是应该在def后加注释说明实现方式
      • 结尾的3引号“”“应该单独列一行(只有一行的除外)
  • 命名规范
    • 不要使用大写的i,小写的L,和大写的O单独命名
    • 满足ASCII规则下
    • 模块和包应该尽量短,且使用全小写方式,下划线的方式不提倡
    • 类命名应该首字母大写(内置类除外)
    • _co or _contra来区分正反意
    • 全局变量名:使用from M import *时,应在M中有__all__机制来阻止全局变量的导出
    • 函数名:全小写,下划线区分,一个下划线区分私有变量和私有方法
    • 函数和方法变量:在实例方法中永远使用self作为第一个参数,在类方法中永远使用cls做第一个参数
    • 如果Foo类中有一个__a的属性,Foo.__a是访问不到该属性的,(Foo.__Foo__a是可以访问到),双下划线应该仅仅被用于设计为子类的类的命名冲突中
    • 常量全大写:MAX_OVERFLOWTOTAL.
    • 继承:公共属性无下划线
原文地址:https://www.cnblogs.com/BigJ/p/7655149.html