最常见的Python文档字符串格式有哪些?
我看到过几种不同的写Python文档字符串的风格,最流行的风格有哪些呢?
6 个回答
关于文档字符串的写法规范,可以参考PEP-257,里面的内容比PEP-8要详细得多。
不过,文档字符串似乎比代码的其他部分更具个人风格。不同的项目会有自己的标准。
我通常都会加上文档字符串,因为它们能很快展示这个函数的用法和功能。
我喜欢保持一致性,不管字符串的长度如何。我觉得代码在缩进和空格一致时看起来更整齐。这意味着,我会使用:
def sq(n):
"""
Return the square of n.
"""
return n * n
而不是:
def sq(n):
"""Returns the square of n."""
return n * n
而且在较长的文档字符串中,我倾向于省略第一行的注释:
def sq(n):
"""
Return the square of n, accepting all numeric types:
>>> sq(10)
100
>>> sq(10.434)
108.86835599999999
Raises a TypeError when input is invalid:
>>> sq(4*'435')
Traceback (most recent call last):
...
TypeError: can't multiply sequence by non-int of type 'str'
"""
return n*n
这意味着我觉得像这样开头的文档字符串看起来很乱。
def sq(n):
"""Return the squared result.
...
谷歌的风格指南里有一个很棒的Python风格指南。里面有关于如何写清晰的文档字符串的规范,这些规范比PEP-257提供的指导要好。例如:
def square_root(n):
"""Calculate the square root of a number.
Args:
n: the number to get the square root of.
Returns:
the square root of n.
Raises:
TypeError: if n is not a number.
ValueError: if n is negative.
"""
pass
我喜欢在参数中加入类型信息,这样可以让代码更清晰,具体的做法可以参考这个Sphinx文档教程。例如:
def add_value(self, value):
"""Add a new value.
Args:
value (str): the value to add.
"""
pass
格式
Python 的文档字符串可以用几种不同的格式来写,之前的帖子也提到过。不过,默认的 Sphinx 文档字符串格式没有被提到,它是基于 reStructuredText (reST) 的。你可以在 这篇博客 中找到关于主要格式的一些信息。
需要注意的是,reST 是 PEP 287 推荐的格式。
接下来是一些常用的文档字符串格式。
- Epytext
历史上,类似于 javadoc 的风格比较流行,所以它被用作 Epydoc(称为 Epytext
格式)生成文档的基础。
示例:
"""
This is a javadoc style.
@param param1: this is a first param
@param param2: this is a second param
@return: this is a description of what is returned
@raise keyError: raises an exception
"""
- reST
现在,可能更常用的格式是 reStructuredText(reST),它被 Sphinx 用来生成文档。
注意:在 JetBrains PyCharm 中默认使用这个格式(在定义方法后输入三重引号并按回车)。在 Pyment 中也默认使用这个格式作为输出。
示例:
"""
This is a reST style.
:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
"""
Google 有自己的一种 格式,经常被使用。它也可以被 Sphinx 解析(也就是使用 Napoleon 插件)。
示例:
"""
This is an example of Google style.
Args:
param1: This is the first param.
param2: This is a second param.
Returns:
This is a description of what is returned.
Raises:
KeyError: Raises an exception.
"""
甚至还有 更多示例
- Numpydoc
需要注意的是,Numpy 推荐遵循他们自己的 numpydoc 格式,这个格式是基于 Google 的,并且可以被 Sphinx 使用。
"""
My numpydoc description of a kind
of very exhautive numpydoc format docstring.
Parameters
----------
first : array_like
the 1st param name `first`
second :
the 2nd param
third : {'value', 'other'}, optional
the 3rd param, by default 'value'
Returns
-------
string
a value in a string
Raises
------
KeyError
when a key error
OtherError
when an other error
"""
转换/生成
可以使用像 Pyment 这样的工具,自动为尚未文档化的 Python 项目生成文档字符串,或者将现有的文档字符串(可以是混合多种格式)从一种格式转换为另一种格式。
注意:示例来自 Pyment 文档