3 种不同的 Python 文档字符串格式


3 种不同的 Python 文档字符串格式

文章插图
 
Python 正在成为当今流行的编程语言 。对于任何编码项目,文档是提高代码可读性的最重要部分,但同时也是最被忽略的部分! 为了解决这个问题,Sphinx 工具派上用场了,它可以自动化文档部分
现在您已经了解 Sphinx 并知道如何使用它 。让我们知道最常用的文档字符串格式,即 google、NumPy 和 Sphinx 文档字符串格式 。
 
1.Google Docstring
这种文档字符串格式是可汗学院推荐的,俗称“Google Docstring” 。为了确保文档字符串与 Sphinx 兼容并被 Sphinx 的自动文档识别,请在 conf.py 文件中添加 sphinx.ext.napoleon 扩展名 。文档字符串格式为:
def google_docstrings(num1, num2) -> int:"""Add up two integer numbers.This function simply wraps the ``+`` operator, and does notdo anything interesting, except for illustrating whatthe docstring of a very simple function looks like.Args:num1 (int) : First number to add.num2 (int) : Second number to add.Returns:The sum of ``num1`` and ``num2``.Raises:AnyError: If anything bad hAppens."""return num1 + num2 
2. NumPy 文档字符串
这种文档格式用于 NumPy、SciPy 和 Pandas 等主要数据科学库 。就像 Google 的文档字符串一样,要使其与 Sphinx 兼容,您必须在 conf.py 文件中添加 sphinx.ext.napoleon 扩展名 。文档字符串的格式为:
def numpy_docstrings(num1, num2) -> int:"""Add up two integer numbers.This function simply wraps the ``+`` operator, and does notdo anything interesting, except for illustrating whatthe docstring of a very simple function looks like.Parameters----------num1 : intFirst number to add.num2 : intSecond number to add.Returns-------intThe sum of ``num1`` and ``num2``.Raises======MyExceptionif anything bad happensSee Also--------subtract : Subtract one integer from another.Examples-------->>> add(2, 2)4>>> add(25, 0)25>>> add(10, -10)0"""return num1 + num2 
3.Sphinx 文档字符串
没有什么比旧的 sphinx 文档字符串更好的了,这是使用的最基本的文档字符串格式,但在视觉上有些密集,因此难以阅读 。相同的格式是:
def sphinx_docstrings(num1, num2) -> int:"""Add up two integer numbers.This function simply wraps the ``+`` operator, and does notdo anything interesting, except for illustrating whatthe docstring of a very simple function looks like.:param int num1: First number to add.:param int num2: Second number to add.:returns:The sum of ``num1`` and ``num2``.:rtype: int:raises AnyError: If anything bad happens."""return num1 + num2 
结论
除了上述格式之外,还有许多可用于 Python 的 docstring 格式,我们在这场比赛中没有一个赢家 。
【3 种不同的 Python 文档字符串格式】所以选择你喜欢的格式,不要混合格式,并在整个项目中坚持下去 。我个人最喜欢的是 NumPy 的 Docstring!




    推荐阅读