python代码规范
代码格式
语句
import 语句
- import 语句应该分行书写
# 正确的写法
import os
import sys
# 不推荐的写法
import sys,os
# 正确的写法
from subprocess import Popen, PIPE
- 导入顺序如下: (各模块类型导入之间要有空行分割,各组里面的模块的顺序按模块首字母自上而下升序排列)
- 标准库
- 相关的第三方库
- 本地库
import os
import sys
import msgpack
import zmq
import foo
代码内语句
- 通常每个语句应该独占一行
不过, 如果测试结果与测试语句在一行放得下, 你也可以将它们放在同一行. 如果是if语句, 只有在没有else时才能这样做. 特别地, 绝不要对try/except 这样做, 因为try和except不能放在同一行.
# 正确的写法
if foo: bar(foo)
# 错误的写法
if foo: bar(foo)
else: baz(foo)
try: bar(foo)
except ValueError: baz(foo)
try:
bar(foo)
except ValueError: baz(foo)
缩进
- 每级缩进用4个空格。(绝对不要用tab, 也不要tab和空格混用 (不明白为什么不能用tab??))
- 括号中使用垂直隐式缩进或使用悬挂缩进。
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',
)
行宽/换行
- 每行不超过80个字符,以下情况除外:
- 长的导入模块语句
- 注释里的URL
- 换行可以使用反斜杠,最好使用圆括号
# 推荐写法:
foo_bar(self, width, height, color='black', design=None, x='foo',
emphasis=None, highlight=0)
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong'):
# 如果一个文本字符串在一行放不下, 可以使用圆括号来实现隐式行连接
x = ('这是一个非常长非常长非常长非常长 '
'非常长非常长非常长非常长非常长非常长的字符串')
# 在注释中,如果必要,将长的URL放在一行上
Yes: # See details at
#http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html
No: # See details at
# http://www.example.com/us/developer/documentation/api/content/\
# v2.0/csv_file_name_extension_full_specification.html
空行
- 两行空行用于分割顶层函数和类的定义
- 单个空行用于分割类定义中的方法
EXAMPLE:
# 类的方法定义用单个空行分割,两行空行分割顶层函数和类的定义。
class A(object):
def method1():
pass
def method2():
pass
def method3():
pass
尾随逗号(Trailing commas)
Yes: golomb3 = [0, 1, 3]
Yes: golomb4 = [
0,
1,
4,
6,
]
No: golomb4 = [
0,
1,
4,
6
]
空格
# 不要在逗号, 分号, 冒号前面加空格, 但应该在它们后面加(除了在行尾).
Yes: if x == 4:
print x, y
x, y = y, x
No: if x == 4 :
print x , y
x , y = y , x
# 在二元操作符两边都加上一个空格, 比如赋值(=), 比较(==, <, >, !=, <>, <=, >=, in, not in, is, is not), 布尔(and, or, not). 至于算术操作符两边的空格该如何使用, 需要你自己好好判断. 不过两侧务必要保持一致.
Yes: x == 1
No: x<1
# 当'='用于指示关键字参数或默认参数值时, 不要在其两侧使用空格.
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:
foo = 1000 # 注释
long_name = 2 # 注释不需要对齐
dictionary = {
"foo": 1,
"long_name": 2,
}
No:
foo = 1000 # 注释
long_name = 2 # 注释不需要对齐
dictionary = {
"foo" : 1,
"long_name": 2,
}
括号
- 宁缺毋滥的使用括号。除非是用于实现行连接, 否则不要在返回语句或条件语句中使用括号. 不过在元组两边使用括号是可以的。
Yes: if foo:
bar()
while x:
x = bar()
if x and y:
bar()
if not x:
bar()
return foo
for (x, y) in dict.items(): ...
No: if (x):
bar()
if not(x):
bar()
return (foo)
引号
- 自然语言 使用双引号 “…”,例如错误信息;很多情况还是 unicode,使用u"你好世界"
- 机器标识 使用单引号 ‘…’,例如 dict 里的 key
- 正则表达式 使用原生的双引号 r"…"
- 文档描述 (docstring) 使用三个双引号 “”“…”“”
注释
总体原则,错误的注释不如没有注释。所以当一段代码发生变化时,第一件事就是要修改注释!!!
- 注释块注释块通常应用在代码前,并和代码有同样的缩进。每行以 ‘# ’ 开头, 而且#后面有单个空格。
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])
- 单行注释,至少离开代码2个空格(尽量少使用)
EXAMPLE:
x = x + 1 # Compensate for border
- 文档注释
作为文档的Docstring一般出现在模块头部、函数和类的头部,这样在python中可以通过对象的__doc__对象获取文档。编辑器和IDE也可以根据Docstring给出自动提示。
EXAMPLE:
# 多行文档, 首行首字母大写,结尾的 """ 应该单独成行
"""Return a foobang
Optional plotz says to frobnicate the bizbaz first.
"""
# 单行的文档, 结尾的 """ 在同一行。
"""Return a foobang"""
对函数参数、返回值等的说明采用numpy标准, 如下所示
def func(arg1, arg2):
"""在这里写函数的一句话总结(如: 计算平均值).
这里是具体描述.
参数
----------
arg1 : int
arg1的具体描述
arg2 : int
arg2的具体描述
返回值
-------
int
返回值的具体描述
参看
--------
otherfunc : 其它关联函数等...
示例
--------
示例使用doctest格式, 在`>>>`后的代码可以被文档测试工具作为测试用例自动运行
>>> a=[1,2,3]
>>> print [x + 3 for x in a]
[4, 5, 6]
"""
- 类型注释
EXAMPLE:
Yes:
def func(a: int) -> List[int]:
def func(a: int = 0) -> int:
...
No:
def func(a:int=0) -> int:
...
- TODO注释,为临时代码使用TODO注释, 它是一种短期解决方案。
# TODO(kl@gmail.com): Use a "*" here for string repetition.
# TODO(Zeke) Change this to use relations.
如果你的TODO是"将来做某事"的形式, 那么请确保你包含了一个指定的日期("2009年11月解决")或者一个特定的事件("等到所有的客户都可以处理XML请求就移除这些代码").
命名规范
-
包、模块名: lower_with_under 尽量短
-
类名:CapsWords 大驼峰
注:pyqt5 项目 .ui文件转换成的.py文件,里面的类名虽不符合上述规范,也不要更改
-
常量名:CAPS_WITH_UNDER
-
函数名、变量名:lower_with_under
编程建议
类继承
如果一个类不继承自其它类, 就显式的从object
继承. 嵌套类也一样.
# 继承自 object 是为了使属性(properties)正常工作, 并且这样可以保护你的代码, 使其不受Python潜在不兼容性影响. 这样做也定义了一些特殊的方法, 这些方法实现了对象的默认语义, 包括 __new__, __init__, __delattr__, __getattribute__, __setattr__, __hash__, __repr__, and __str__ .
Yes: class SampleClass(object):
pass
class OuterClass(object):
class InnerClass(object):
pass
class ChildClass(ParentClass):
"""Explicitly inherits from another class already."""
No: class SampleClass:
pass
class OuterClass:
class InnerClass:
pass
比较/判定
- None 的比较用 is 或 is not,而不要用 ==
- 用 is not 代替 not … is, 前者的可读性更好
EXAMPLE:
# Yes
if foo is not None
# No
if not foo is None
- 使用使用
.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
关闭文件
在文件和sockets结束时, 显式的关闭它
# 推荐使用 "with"语句 以管理文件:
with open("hello.txt") as hello_file:
for line in hello_file:
print line
# 对于不支持使用"with"语句的类似文件的对象,使用 contextlib.closing():
import contextlib
with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
for line in front_page:
print line
字符串
-
避免在循环中用+和+=操作符来累加字符串。
由于字符串是不可变的, 这样做会创建不必要的临时对象, 并且导致二次方而不是线性的运行时间. 作为替代方案, 你可以将每个子串加入列表, 然后在循环结束后用 .join 连接列表. (也可以将每个子串写入一个 cStringIO.StringIO 缓存中.)
Yes: x = a + b
x = '%s, %s!' % (imperative, expletive)
x = '{}, {}!'.format(imperative, expletive)
x = 'name: %s; score: %d' % (name, n)
x = 'name: {}; score: {}'.format(name, n)
No: x = '%s%s' % (a, b) # use + in this case
x = '{}{}'.format(a, b) # use + in this case
x = imperative + ', ' + expletive + '!'
x = 'name: ' + name + '; score: ' + str(n)
Yes: items = ['<table>']
for last_name, first_name in employee_list:
items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name))
items.append('</table>')
employee_table = ''.join(items)
No: employee_table = '<table>'
for last_name, first_name in employee_list:
employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name)
employee_table += '</table>'
- 在同一个文件中, 保持使用字符串引号的一致性
Yes:
Python('Why are you hiding your eyes?')
Gollum("I'm scared of lint errors.")
Narrator('"Good!" thought a happy Python reviewer.')
No:
Python("Why are you hiding your eyes?")
Gollum('The lint. It burns. It burns us.')
Gollum("Always the great lint. Watching. Watching.")
异常
- 异常类应该继承自Exception,而不是 BaseException
- 捕获异常时尽量指明具体异常, 尽量不用
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
pycharm代码格式化快捷键
Ctrl+Alt+O : 优化import语句
Ctrl+Alt+L : 优化代码格式(注释、空行、空格等)
参考资料
(92条消息) jupyter notebook书写规范_treelly的博客-CSDN博客