小编典典

标准的Python文档字符串格式是什么?

python

我已经看到了几种用Python编写文档字符串的不同样式,是否有正式的或“同意的”样式?


阅读 653

收藏
2020-02-23

共1个答案

小编典典

格式

可以按照其他文章所示的几种格式编写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

如今,可能更流行的格式是Sphinx用于生成文档的reStructuredText(reST)格式。注意:它在JetBrains PyCharm中默认使用(在定义方法后键入三引号并按Enter键)。默认情况下,它也用作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

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建议根据Google格式使用自己的numpydoc,并且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项目生成文档字符串,或将现有文档字符串(可以混合多种格式)从一种格式转换为另一种格式。

2020-02-23