python 书写规范
1. 基础规则
1.1 编码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#####################################################
# Title: xxxx.py
# Author:
# Creat Date: 2018-06-27
# Modify Author:
# Modify Date:
# Python Version: 2.7
#####################################################
1.2 布局
1.2.1 缩进与换行
(1)用四个空格表示缩进;
(2)括号内的换行,缩进方式分为垂直隐式缩进或悬挂缩进;
(3)行宽一般不超过80个字符,对于长字符串可使用“\”进行换行;
(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)
#对于if判断语句的缩进方式,添加额外缩进以示区别;
if (this_is_one_thing
and that_is_another_thing):
do_something()
# 右括号回退
my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)
# 正确的写法
if foo == 'blah':
do_blah_thing()
# 不推荐的写法
if foo == 'blah': do_blash_thing()
1.2.2 空格
(1)在二元运算符两边各空一格[=,-,+=,==,>,in,is not, and]: ;
(2)函数的参数列表中“,”之后要有空格;
(3)字典对象的左括号之前不要多余的空格;
(4)不要为对齐赋值语句而使用的额外空格。
#运算符前后的空格
i = i + 1
submitted += 1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
#函数参数后的空格
def complex(real, imag):
pass
#字典的key值
dict['key'] = list[index]
#赋值语句的对其方式
x = 1
y = 2
long_variable = 3
1.2.3 空行
(1)模块级函数和类定义之间空两行;
(2)类成员函数之间空一行;
(3)额外的空行可用于分割不同的函数组;
(4)额外的空行在函数中可用于区分不同的逻辑块(i.e. if, while, for, def 等)。
class A:
def __init__(self):
pass
def hello(self):
pass
def main():
pass
1.2.4 import
(1)import语句应分行书写;
(2)import语句应该放在文件头部,置于模块说明及docstring之后,于全局变量之前;
(3)import 导入顺序为:标准库,第三方库,自定义库,不同类型的库之间用空行隔开;
import os
import sys
import re
from subprocess import Popen, PIPE
from myclass import MyClass
from NIPT.util import combine
2. 注释
2.1 局部注释
2.1.1 块注释
(1)注释块通常应用在代码前,并和这些代码有同样的缩进。每行以 '# '(除非它是注释内的缩进文本,注意#后面有空格)。
2.1.2 行注释
(1)至少使用两个空格和语句分开,注意不要使用无意义的注释
2.1.3 建议
(1)比较重要的注释段, 使用多个等号隔开, 可以更加醒目, 突出重要性
# 块注释
# 块注释
#
# 块注释
x = x + 1 # 边框加粗一个像素
# =====================================
# 请勿在此处添加 get post等app路由行为 !!!
# =====================================
2.1 文档注释(Docstring)
(1)文档注释通常置于模块头部、函数和类的头部,这样在python中可以通过对象的doc对象获取文档;
(2)文档注释以 """ 开头和结尾, 首行不换行, 如有多行, 末行必需换行;
"""Example docstrings.
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 NIPT-plus.py <input> <output>
Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime a new section starts.
"""
(3)对于定义函数的文档注释,要具体表述其内容、参数、返回值等;
(4)模块、公有类、公有方法, 能写文档注释的, 尽量附上简练的文档注释。
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]
"""
3. 命名规则
3.1 模块和包
(1)模块尽量使用小写字母命名,首字母保持小写,尽量不要用下划线(除非多个单词,且数量不多的情况);包名和模块名类似,但不推荐使用下划线。
#模块的命名
import decoder
import html_parser
#包的命名
from package1 import module1
3.2 类名
(1)类名使用驼峰(CamelCase)命名风格,首字母大写,私有类可用一个下划线开头;
class Farm():
pass
class AnimalFarm(Farm):
pass
class _PrivateFarm(Farm):
pass
3.3 函数名
(1)函数名一律小写,如有多个单词,用下划线隔开;
(2)私有函数在函数前加一个下划线“_” 。
def run():
pass
def run_with_env():
pass
#私有函数的命名
class Person():
def _private_func():
pass
3.4 变量名与常量名
(1)变量名尽量小写, 如有多个单词,用下划线隔开;
(2)常量采用全大写,如有多个单词,使用下划线隔开。
#变量的命名规则
if __name__ == '__main__':
count = 0
school_name = ''
#常量的命名规则
MAX_CLIENT = 100
MAX_CONNECTION = 1000
CONNECTION_TIMEOUT = 600
4. 编程习惯
(1)捕获异常时尽量指明具体异常,而不是空"except:"子句;python 2.6以后支持用按时支出具体的异常名;
try:
import platform_specific_module
except ImportError as exc:
platform_specific_module = None
(2)函数或者方法在没有返回时要明确返回None;
def foo(x):
if x >= 0:
return math.sqrt(x)
else:
return Nonedef bar(x):
if x < 0:
return None
return math.sqrt(x)
(3)使用 .startswith()和.endswith()代替字符串切片来检查前缀和后缀;
# startswith 更为简洁
if foo.startswith('bar'):
# 切片的方式容易出错
if foo[:3] == 'bar':
(4)不要用 “==” 进行布尔比较
if greeting::
pass
# No
if greeting == True
pass
# Worse
if greeting is True:
pass
网友评论