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

    目录

    代码布局

    缩进

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

    EXAMPLE:

    # (垂直隐式缩进)对准左括号
    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',
    )

    错误示范:

    # 不使用垂直对齐时,第一行不能有参数。
    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',
        )

    最大行宽

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

    EXAMPLE:

    
    # 无括号续行, 利用反斜杠
    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))

    空行

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

    EXAMPLE:

    # 类的方法定义用单个空行分割,两行空行分割顶层函数和类的定义。
    class A(object):
        def method1():
            pass
    
        def method2():
            pass
    
    
    def method3():
        pass

    模块导入

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

    EXAMPLE:

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

    错误示例:

    # 一行导入多模块
    import sys, os, knife
    
    # 不按首字母导入
    import create
    import active
    import beyond

    字符串

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

    EXAMPLE:

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

    表达式和语句中的空格

    • 括号里边避免空格

    EXAMPLE:

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

    错误示例:

    spam( ham[ 1 ], { eggs: 2 } )
    • 逗号,冒号,分号之前避免空格
      EXAMPLE:
    if x == 4: print x, y; x, y = y, x

    错误示例:

    if x == 4 : print x , y ; x , y = y , x
    • 函数调用的左括号之前不能有空格

    EXAMPLE:

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

    错误示例:

    spam (1)
    dct ['key'] = lst [index]
    • 赋值等操作符前后不能因为对齐而添加多个空格

    EXAMPLE:

    x = 1
    y = 2
    long_variable = 3

    错误示例:

    x             = 1
    y             = 2
    long_variable = 3
    • 二元运算符两边放置一个空格
      • 涉及 = 的复合操作符 ( += , -=等)
      • 比较操作符 ( == , < , > , != , <> , <= , >= , in , not in , is , is not )
      • 逻辑操作符( and , or , not )

    EXAMPLE:

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

    注释

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

    EXAMPLE:

    # 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:

    x = x + 1 # Compensate for border
    • 文档字符串

    EXAMPLE:

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

    命名规则

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

    • 类名:
      遵循驼峰命名

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

    EXAMPLE:

    _name = 'name'
    • 函数名
      函数名应该为全部小写的凹驼峰规则。

    EXAMPLE:

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

    EXAMPLE:

    MAX_OVERFLOW = ''
    TOTAL = 1
    • 方法名和实例变量
      • 非公开方法和实例变量开头使用前置下划线
      • 有时候可能会为了避免与子类命名冲突,采用两个前置下划线
        需要注意的是: 若 class Foo 的属性名为 __a, 该属性是不能以 Foo.__a 的方式访问的(执著的用户还是可以通过Foo._Foo__a 来访问), 所以通常双前置下划线仅被用来避免与基类的属性发生命名冲突。

    编程建议

    • None 的比较用 isis not,而不要用 ==

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

    EXAMPLE:

    # Yes
    if foo is not None
    
    # No
    if not foo is None
    • 使用函数定义关键字 def 代替 lambda 赋值给标识符, 这样更适合于回调和字符串表示
    # 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:

    # 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:

    # 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
    # Yes
    def foo():
        return None
    
    # No
    def foo():
        return
    • 使用字符串方法而不是 string 模块
      python 2.0 以后字符串方法总是更快,而且与 Unicode 字符串使用了相同的 API

    • 使用使用 .startswith().endswith() 代替字符串切片来检查前缀和后缀
      startswith()endswith 更简洁,利于减少错误

    EXAMPLE:

    # Yes
    if foo.startswith('bar'):
    
    # No
    if foo[:3] == 'bar':
    • 使用 isinstance() 代替对象类型的比较

    EXAMPLE:

    # Yes
    if isinstance(obj, int):
    
    # No
    if type(obj) is type(1):
    • 空序列类型对象的 bool 为 False:
    # Yes
    if not seq:
       pass
    if seq:
       pass
    
    # No
    if len(seq):
       pass
    if not len(seq):
       pass
    • 不要用 == 进行 bool 比较
    # Yes
    if greeting:
       pass
    
    # No
    if greeting == True
       pass
    if greeting is True: # Worse
       pass
  • 相关阅读:
    Java并发编程:并发容器之ConcurrentHashMap(转载)
    Java ConcurrentModificationException异常原因和解决方法
    Java并发编程:同步容器
    Java并发编程:深入剖析ThreadLocal
    错误:The POM for org.codehaus.plexus:plexus-compiler-api:jar:2.2 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details的解决方法
    maven工程中引入oracle驱动报错Missing artifact com.oracle:ojdbc14:jar:10.2.0.4.0
    部署时发出警告: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:jx-web' did not find a matching property.的解决方法
    [WARNING] The POM for com.tao:jx-service:jar:0.0.1-SNAPSHOT is missing, no dependency information available
    maven工程中警告[WARNING] Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!
    Eclipse中Errors occurred during the build最简单的解决方法
  • 原文地址:https://www.cnblogs.com/jmilkfan-fanguiju/p/10589839.html
Copyright © 2011-2022 走看看