这篇文章主要介绍了 Python 常用 PEP8 编码规范详解的相关资料, 需要的朋友可以参考下
Python 是一种面向对象、解释型计算机程序设计语言,由 Guido van Rossum 于 1989 年底发明,第一个公开发行版发行于 1991 年。Python 语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是 C/C++)很轻松地联结在一起。
Python 常用 PEP8 编码规范
代码布局
缩进
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',
- )
最大行宽
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
二元运算符两边放置一个空格
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 的比较用 is 或 is 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
来源: http://www.phperz.com/article/17/0321/320835.html