zoukankan      html  css  js  c++  java
  • Python 常用 PEP8 编码规范

    Python 常用 PEP8 编码规范

    代码布局

    缩进

    • 每级缩进用4个空格。
    • 括号中使用垂直隐式缩进或使用悬挂缩进。

    EXAMPLE:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    # (垂直隐式缩进)对准左括号
    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)
     
     
     
    # 右括号回退
    my_list = [
     1, 2, 3,
     4, 5, 6,
    ]
    result = some_function_that_takes_arguments(
     'a', 'b', 'c',
     'd', 'e', 'f',
    )

    错误示范:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    # 不使用垂直对齐时,第一行不能有参数。
    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)
     
    # 右括号不回退,不推荐
    my_list = [
     1, 2, 3,
     4, 5, 6,
     ]
     
    result = some_function_that_takes_arguments(
     'a', 'b', 'c',
     'd', 'e', 'f',
     )

    最大行宽

    1. 每行最大行宽不超过 79 个字符
    2. 一般续行可使用反斜杠
    3. 括号内续行不需要使用反斜杠

    EXAMPLE:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    # 无括号续行, 利用反斜杠
    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())
     
    # 括号内续行, 尽量在运算符后再续行
    class Rectangle(Blob):
     
     def __init__(self, width, height,
       color='black', emphasis=None, highlight=0):
     if (width == 0 and height == 0 and
      color == 'red' and emphasis == 'strong' or
      highlight > 100):
      raise ValueError("sorry, you lose")
     if width == 0 and height == 0 and (color == 'red' or
          emphasis is None):
      raise ValueError("I don't think so -- values are %s, %s" %
        (width, height))

    空行

    1. 两行空行用于分割顶层函数和类的定义
    2. 单个空行用于分割类定义中的方法

    EXAMPLE:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    # 类的方法定义用单个空行分割,两行空行分割顶层函数和类的定义。
    class A(object):
     def method1():
     pass
     
     def method2():
     pass
     
     
    def method3():
     pass

    模块导入

    1. 导入的每个模块应该单独成行
    2. 导入顺序如下: (各模块类型导入之间要有空行分割,各组里面的模块的顺序按模块首字母自上而下升序排列) 
    1. 标准库
    2. 相关的第三方库
    3. 本地库

    EXAMPLE:

    1
    2
    3
    4
    # 按模块首字母排序导入, 依此递推
    import active
    import adidas
    import create

    错误示例:

    1
    2
    3
    4
    5
    6
    7
    # 一行导入多模块
    import sys, os, knife
     
    # 不按首字母导入
    import create
    import active
    import beyond

    字符串

    单引号和双引号作用是一样的,但必须保证成对存在,不能夹杂使用. (建议句子使用双引号, 单词使用单引号, 但不强制.)

    EXAMPLE:

    1
    2
    3
    # 单引号和双引号效果一样
    name = 'JmilkFan'
    name = "Hey Guys!"

    表达式和语句中的空格

    括号里边避免空格

    EXAMPLE:

    1
    spam(ham[1], {eggs: 2})

    错误示例:

    1
    spam( ham[ 1 ], { eggs: 2 } )

    逗号,冒号,分号之前避免空格 

    EXAMPLE:

    1
    if x == 4: print x, y; x, y = y, x

    错误示例:

    1
    if x == 4 : print x , y ; x , y = y , x

    函数调用的左括号之前不能有空格

    EXAMPLE:

    1
    2
    spam(1)
    dct['key'] = lst[index]

    错误示例:

    1
    2
    spam (1)
    dct ['key'] = lst [index]

    赋值等操作符前后不能因为对齐而添加多个空格

    EXAMPLE:

    1
    2
    3
    x = 1
    y = 2
    long_variable = 3

    错误示例:

    1
    2
    3
    = 1
    = 2
    long_variable = 3

    二元运算符两边放置一个空格 

    1. 涉及 = 的复合操作符 ( += , -=等)
    2. 比较操作符 ( == , < , > , != , <> , <= , >= , in , not in , is , is not )
    3. 逻辑操作符( and , or , not )

    EXAMPLE:

    1
    2
    3
    4
    5
    a = b
    a or b
     
    # 括号内的操作符不需要空格
    name = get_name(age, sex=None, city=Beijing)

    注释

    注释块

    注释块通常应用在代码前,并和代码有同样的缩进。每行以 ‘# ' 开头, 而且#后面有单个空格。

    EXAMPLE:

    1
    2
    3
    4
    # Have to define the param `args(List)`,
    # otherwise will be capture the CLI option when execute `python manage.py server`.
    # oslo_config: (args if args is not None else sys.argv[1:])
    CONF(args=[], default_config_files=[CONFIG_FILE])

    单行注释(应避免无谓的注释)

    EXAMPLE:

    1
    x = x + 1 # Compensate for border

    文档字符串

    EXAMPLE:

    1
    2
    3
    4
    5
    6
    7
    # 多行文档, 首行首字母大写,结尾的 """ 应该单独成行
    """Return a foobang
    Optional plotz says to frobnicate the bizbaz first.
    """
     
    # 单行的文档, 结尾的 """ 在同一行。
    """Return a foobang"""

    命名规则

    包和模块名: 

    包和模块名应该简短,全部用小写字母, 多字母之间可以使用单下划线连接。

    类名: 

    遵循驼峰命名

    1
    2
    class MyClass(object):
     pass

    全局变量名: 

    全局变量名应尽量只在模块内部使用, 对可能使用语句 from moduleName import variableName 而被导入的模块,应采用 __all__ 机制来防止全局变量被别的模块导入, 或者在全局变量名开头加一个前置下划线.

    EXAMPLE:

    1
    _name = 'name'

    函数名 

    函数名应该为全部小写的凹驼峰规则。

    EXAMPLE:

    1
    vcenter_connection = ''

    常量名 

    常量全部使用大写字母的凹驼峰规则来表示, 通常在模块顶格定义

    EXAMPLE:

    1
    2
    MAX_OVERFLOW = ''
    TOTAL = 1

    方法名和实例变量 

    非公开方法和实例变量开头使用前置下划线

    有时候可能会为了避免与子类命名冲突,采用两个前置下划线 

    需要注意的是: 若 class Foo 的属性名为 __a, 该属性是不能以 Foo.__a 的方式访问的(执著的用户还是可以通过Foo._Foo__a 来访问), 所以通常双前置下划线仅被用来避免与基类的属性发生命名冲突。

    编程建议

    None 的比较用 is 或 is not,而不要用 ==

    用 is not 代替 not … is, 前者的可读性更好

    EXAMPLE:

    1
    2
    3
    4
    5
    # Yes
    if foo is not None
     
    # No
    if not foo is None

    使用函数定义关键字 def 代替 lambda 赋值给标识符, 这样更适合于回调和字符串表示

    1
    2
    3
    4
    5
    6
    # Yes
    def f(x):
     return 2*x
     
    # No
    f = lambda x: 2*x

    异常类应该继承自Exception,而不是 BaseException

    Python 2 中用raise ValueError('message') 代替 raise ValueError, 'message'

    (考虑兼容python3和续行的方便性)

    捕获异常时尽量指明具体异常, 尽量不用 except Exception, 应该捕获 出了什么问题,而不是 问题发生

    EXAMPLE:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    # Yes (捕获具体异常)
    try:
     import platform_specific_module
    except ImportError:
     platform_specific_module = None
     
    # No (不要全局捕获)
    try:
     import platform_specific_module
    except:
     platform_specific_module = None

    try/except 子句中的代码要尽可能的少, 以免屏蔽掉其他的错误

    EXAMPLE:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    # Yes
    try:
     value = collection[key]
    except KeyError:
     return key_not_found(key)
    else:
     return handle_value(value)
     
    # No
    try:
     return handle_value(collection[key])
    except KeyError:
     # 可能会捕捉到 handle_value()中的 KeyError, 而不是 collection 的
     return key_not_found(key)

    函数或者方法在没有返回值时要明确返回 None

    1
    2
    3
    4
    5
    6
    7
    # Yes
    def foo():
     return None
     
    # No
    def foo():
     return

    使用字符串方法而不是 string 模块 

    python 2.0 以后字符串方法总是更快,而且与 Unicode 字符串使用了相同的 API

    使用使用 .startswith() 和 .endswith() 代替字符串切片来检查前缀和后缀

    startswith() 和 endswith 更简洁,利于减少错误

    EXAMPLE:

    1
    2
    3
    4
    5
    # Yes
    if foo.startswith('bar'):
     
    # No
    if foo[:3] == 'bar':

    使用 isinstance() 代替对象类型的比较

    EXAMPLE:

    1
    2
    3
    4
    5
    # Yes
    if isinstance(obj, int):
     
    # No
    if type(obj) is type(1):

    空序列类型对象的 bool 为 False:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    # Yes
    if not seq:
     pass
    if seq:
     pass
     
    # No
    if len(seq):
     pass
    if not len(seq):
     pass

    不要用 == 进行 bool 比较

    1
    2
    3
    4
    5
    6
    7
    8
    9
    # Yes
    if greeting:
     pass
     
    # No
    if greeting == True
     pass
    if greeting is True: # Worse
     pass
  • 相关阅读:
    tomcat做成windows服务之后使用JMX监控的问题
    Spring CORS
    人大金仓
    今天遇到奇怪的事:SVN本地代码的标记突然没了,Clean up也报错
    你真得懂Javascript中的==等于运算符吗?
    Codeforces 384E 线段树+dfs序
    一个图形引擎的画面风格是由那些因素(技术)决定的?
    【BZOJ 1146】【CTSC 2008】网络管理network
    ajax核心技术1---XMLHttpRequset对象的使用
    Android中Application类的详解:
  • 原文地址:https://www.cnblogs.com/xuaijun/p/7985892.html
Copyright © 2011-2022 走看看