情景描述:
项目中,发现很多函数、类没有注释说明,一个个弄比较繁琐,所以……
docstring
定义:
官方:A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the doc special attribute of that object;
人话:“出现在模块、函数、类、方法里的第一个语句,就叫做docsting
”;
调用:使用__doc__
。
1
2
3
4
5 def foo():
""" This is function foo"""
foo.__doc__
# This is function foo
docstring
风格:
主要四种:
javadoc
(Epytext
),reST
,numpydoc
,
1 | # Epytext |
转换工具pyment
用来创建、转换
docsting
,点击查看安装
centos中可能使用不了patch
,点击下载安装包pyment
命令帮助:pyment -h
1 | # 安装pyment |
例子:
注释前
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 # test.py
def func(param1=True, param2='default val'):
'''Description of func with docstring groups style.
Params:
param1 - descr of param1 that has True for default value.
param2 - descr of param2
Returns:
some value
Raises:
keyError: raises key exception
TypeError: raises type exception
'''
pass
class A:
def method(self, param1, param2=None):
pass
执行
pyment test.py
,得到patch
文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 # Patch generated by Pyment v0.2.0
--- a/test.py
+++ b/test.py
@@ -1,20 +1,22 @@
def func(param1=True, param2='default val'):
- '''Description of func with docstring groups style.
+ """Description of func with docstring groups style.
- Params:
- param1 - descr of param1 that has True for default value.
- param2 - descr of param2
+ :param param1: descr of param1 that has True for default value
+ :param param2: descr of param2 (Default value = 'default val')
+ :returns: some value
+ :raises keyError: raises key exception
+ :raises TypeError: raises type exception
- Returns:
- some value
-
- Raises:
- keyError: raises key exception
- TypeError: raises type exception
-
- '''
+ """
pass
class A:
+ """ """
def method(self, param1, param2=None):
+ """
+
+ :param param1:
+ :param param2: (Default value = None)
+
+ """
pass
执行
patch -p1 < test.py.patch
,注释后得到
1 | def func(param1=True, param2='default val'): |
后续
使用
sphinx
的autodoc
自动从docstring
生产api文档, 避免重复工作,再娄一遍Api文档。