文章目录
一、代码格式
1. 编码
- 统一使用 UTF-8 编码(无特殊情况)
- 文件头部必须加入#--coding:utf-8--标识(无特殊情况)
# -*- coding: utf-8 -*-
2. 缩进
- 统一使用4个空格,勿使用tab键
3. 行宽
- 每行代码尽量不超过 80 个字符
- 以下特殊情况可超过 80 ,但不得超过 120
- 长的导入模块语句
- 注释里的URL
4. 引号
自然语言使用双引号,机器标示使用单引号
# 自然语言 使用双引号 "..."
a = u"你好世界"
# 机器标识 使用单引号 '...'
b = {'tt': a}
# 正则表达式 使用原生的双引号 r"..."
c = r'(.*) are (.*?) .*'
# 文档字符串 (docstring) 使用三个双引号 """......"""
d = """aaaaaaaaaaaaaa
bbbbbbbbbbbbbbb
"""
5. 空行
- 模块级函数和类定义之间空两行
- 类成员函数之间空一行
- 可以使用多个空行分隔多组相关的函数
- 函数中可以使用空行分隔出逻辑相关的代
class A:
def __init__(self):
pass
def hello(self):
pass
def main():
pass
6 换行
- 括号内的换行
- 第二行缩进到括号的起始处
- 第二行缩进 4 个空格,适用于起始括号就换行的情形
# 第一种情况
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)
- 使用反斜杠\换行,二元运算符+.等应出现在行末;长字符串也可以用此法换行(不建议使用\换行,尽量使用括号或"""""")
# 不建议使用
session.query(MyTable).\
filter_by(id=1).\
one()
print 'Hello, '\
'%s %s!' %\
('Harry', 'Potter')
# 建议使用
(session.query(MyTable).
filter_by(id=1).
one())
print ('Hello,
%s %s!' %
('Harry', 'Potter'))
- 禁止复合语句,即一行中包含多个语句
# 正确的写法
do_first()
do_second()
do_third()
# 不推荐的写法
do_first();do_second();do_third();
- if/for/while一定要换行
# 正确的写法
if foo == 'blah':
do_blah_thing()
# 不推荐的写法
if foo == 'blah': do_blash_thing()
7. 缩进
用4个空格来缩进代码
# 正确的写法
# 与起始变量对齐
foo = long_function_name(var_one, var_two,
var_three, var_four)
# 字典中与起始值对齐
foo = {
long_dictionary_key: value1 +
value2,
...
}
# 4 个空格缩进,第一行不需要
foo = long_function_name(
var_one, var_two, var_three,
var_four)
# 字典中 4 个空格缩进
foo = {
long_dictionary_key:
long_dictionary_value,
...
}
# 不推荐的写法
# 第一行有空格是禁止的
foo = long_function_name(var_one, var_two,
var_three, var_four)
# 2 个空格是禁止的
foo = long_function_name(
var_one, var_two, var_three,
var_four)
# 字典中没有处理缩进
foo = {
long_dictionary_key:
long_dictionary_value,
...
}
8. 括号
不要在返回语句或条件语句中使用括号.
# 正确的写法
if foo:
do_blah_thing()
# 不推荐的写法
if (foo):
do_blah_thing()
9. 空格
- 在二元运算符两边各空一格[=,-,+=,==,>,in,is not, and]:
# 正确的写法
i = i + 1
submitted += 1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
# 不推荐的写法
i=i+1
submitted +=1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)
- 函数的参数列表中,之后要有空格
# 正确的写法
def complex(real, imag):
pass
# 不推荐的写法
def complex(real,imag):
pass
- 函数的参数列表中,默认值等号两边不要添加空格
# 正确的写法
def complex(real, imag=0.0):
pass
# 不推荐的写法
def complex(real, imag = 0.0):
pass
- 左括号之后,右括号之前不要加多余的空格
# 正确的写法
spam(ham[1], {eggs: 2})
# 不推荐的写法
spam( ham[1], { eggs : 2 } )
- 字典对象的左括号之前不要多余的空格
# 正确的写法
dict['key'] = list[index]
# 不推荐的写法
dict ['key'] = list [index]
- 不要为对齐赋值语句而使用的额外空格
# 正确的写法
x = 1
y = 2
long_variable = 3
# 不推荐的写法
x = 1
y = 2
long_variable = 3
二、文档格式
1. docstring
- 所有的公共模块、函数、类、方法,都应该写docstring。私有方法不一定需要,但应该在 def 后提供一个块注释来说明。
- docstring 的结束"""应该独占一行,除非此 docstring只有一行。
"""Return a foobar
Optional plotz says to frobnicate the bizbaz first.
"""
"""Oneline docstring"""
2. import语句
- import 语句应该分行书写
# 正确的写法
import os
import sys
# 不推荐的写法
import sys,os
# 正确的写法
from subprocess import Popen, PIPE
- import语句应该使用 absolute import
# 正确的写法
from foo.bar import Bar
# 不推荐的写法
from ..bar import Bar
- import语句应该放在文件头部,置于模块说明及docstring之后,于全局变量之前;
- import语句应该按照顺序排列,每组之间用一个空行分隔
import os
import sys
import msgpack
import zmq
import foo
- 导入其他模块的类定义时,可以使用相对导入
from myclass import MyClass
- 如果发生命名冲突,则可使用命名空间
import bar
import foo.bar
bar.Bar()
foo.bar.Bar()
- 导入应该按照从最通用到最不通用的顺序分组,每种分组中, 应该根据每个模块的完整包路径按字典序排序, 忽略大小写.
- 标准库导入
- 第三方库导入
- 应用程序指定导入
四、注释
1. 块注释
“#”号后空一格,段落件用空行分开(同样需要“#”号)
# 块注释
# 块注释
#
# 块注释
# 块注释
2. 单行注释
至少使用两个空格和语句分开,注意不要使用无意义的注释
# 正确的写法
x = x + 1 # 边框加粗一个像素
# 不推荐的写法(无意义的注释)
x = x + 1 # x加1
3. 多行注释
"""
xxxx
xxxxxxx
xxxxxxxxxx
"""
/*
xxx
xxxxx
*/
比较重要的注释段, 使用多个等号隔开, 可以更加醒目, 突出重要性
app = create_app(name, options)
# =====================================
# 请勿在此处添加 get post等app路由行为 !!!
# =====================================
if __name__ == '__main__':
app.run()
4. 特殊注释
#!/usr/bin/env python
#-*-coding:utf-8-*-
5. 文档注释(Docstring)
文档注释以 “”" 开头和结尾, 首行不换行, 如有多行, 末行必需换行
"""
This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with a section header and a colon followed by a block of indented text.
Example:
Examples can be given using either the ``Example`` or ``Examples``
sections. Sections support any reStructuredText formatting, including
literal blocks::
$ python example_google.py
Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime a new section starts.
"""
6. 函数或方法注释
def xxx_xxx(arg1, arg2=None):
"""xxxxxx.(基本描述)
xxxxxxxxxxxxxxxxxxx.(详细描述)
Args:(参数说明)
arg1: xxx(类型)
xxxxxx(详细描述).
arg2: xxx(类型)
xxxxxx(详细描述).
Return:(返回值说明)
xxxxxxxxxxxxxx. For example:
{xxx:{}, xxx{}}
Example:(示例)
xxxxxxxxxxxxxxxx(使用doctest格式, 在`>>>`后的代码可以被文档测试工具作为测试用例自动运行)
>>> a = [1, 2, 3]
>>> print [x + 3 for x in a]
[4, 5, 6]
Raises:(可能的异常)
IOError: An error occurred acessing the bigtable. Table object.
"""
7. 类注释
class XxxXxx(object):
"""xxxxxxxx(基本描述)
xxxxxxxxxxxxxxxxxxx(详细描述)
Attributes:(属性说明)
attr1:xxxxx
attr2:xxxxx
"""
def __init__(self, attr1=False):
"""Inits SampleClass with blah."""
self.attr1 = attr1
self.attr2 = attr2
五、命名规范
1. 模块
模块尽量使用小写命名,首字母保持小写,尽量不要用下划线(除非多个单词,且数量不多的情况)
# 正确的模块名
import decoder
import html_parser
# 不推荐的模块名
import Decoder
2. 类名
类名使用驼峰(CamelCase)命名风格,首字母大写,私有类可用一个下划线开头
class Farm():
pass
class AnimalFarm(Farm):
pass
class _PrivateFarm(Farm):
pass
3. 函数
- 函数名一律小写,如有多个单词,用下划线隔开
def run():
pass
def run_with_env():
pass
- 私有函数在函数前加一个下划线_
class Person():
def _private_func():
pass
4. 变量名
- 变量名尽量小写, 如有多个单词,用下划线隔开
if __name__ == '__main__':
count = 0
school_name = ''
- 常量采用全大写,如有多个单词,使用下划线隔开
MAX_CLIENT = 100
MAX_CONNECTION = 1000
CONNECTION_TIMEOUT = 600