# 正确的写法
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)
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',
)
# 推荐写法:
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
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)
总体原则,错误的注释不如没有注释。所以当一段代码发生变化时,第一件事就是要修改注释!!!
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
作为文档的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([email protected]): 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
Python之父Guido推荐的规范
如果一个类不继承自其它类, 就显式的从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
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):
# Yes
if not seq:
pass
if seq:
pass
# No
if len(seq):
pass
if not len(seq):
pass
# 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 = ['']
for last_name, first_name in employee_list:
items.append('%s, %s ' % (last_name, first_name))
items.append('
')
employee_table = ''.join(items)
No: employee_table = ''
for last_name, first_name in employee_list:
employee_table += '%s, %s ' % (last_name, first_name)
employee_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.")
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
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)
# Yes
def foo():
return None
# No
def foo():
return
Ctrl+Alt+O : 优化import语句
Ctrl+Alt+L : 优化代码格式(注释、空行、空格等)
(92条消息) jupyter notebook书写规范_treelly的博客-CSDN博客
Python 常用 PEP8 编码规范和建议-阿里云开发者社区 (aliyun.com)
Python代码书写规范 - 写忆 - 博客园 (cnblogs.com)