如何为带参数的方法编写文档?
如何用Python的文档字符串来记录带参数的方法?
PEP 257给出了这个例子:
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0: return complex_zero
...
这是大多数Python开发者使用的规范吗?
Keyword arguments:
<parameter name> -- Definition (default value if any)
我原本期待的是一些更正式的东西,比如
def complex(real=0.0, imag=0.0):
"""Form a complex number.
@param: real The real part (default 0.0)
@param: imag The imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0: return complex_zero
...
环境:Python 2.7.1
9 个回答
40
约定:
工具:
更新:从Python 3.5开始,你可以使用类型提示,这是一种简洁、机器可读的语法:
from typing import Dict, Union
def foo(i: int, d: Dict[str, Union[str, int]]) -> int:
"""
Explanation: this function takes two arguments: `i` and `d`.
`i` is annotated simply as `int`. `d` is a dictionary with `str` keys
and values that can be either `str` or `int`.
The return type is `int`.
"""
这种语法的主要优点是它是由语言本身定义的,而且没有歧义,因此像PyCharm这样的工具可以轻松利用它。
280
因为文档字符串是自由格式的,所以生成API文档时,具体取决于你使用什么工具来解析代码。
我建议你熟悉一下Sphinx标记语言,因为它被广泛使用,已经成为记录Python项目的事实标准,部分原因是它与优秀的readthedocs.org服务结合得很好。为了简单地说一下Sphinx文档中的一个例子,我们可以用Python代码片段来表示:
def send_message(sender, recipient, message_body, priority=1) -> int:
"""
Send a message to a recipient.
:param str sender: The person sending the message
:param str recipient: The recipient of the message
:param str message_body: The body of the message
:param priority: The priority of the message, can be a number 1-5
:type priority: integer or None
:return: the message id
:rtype: int
:raises ValueError: if the message_body exceeds 160 characters
:raises TypeError: if the message_body is not a basestring
"""
这种标记语言支持文档之间的交叉引用等功能。需要注意的是,Sphinx文档中使用的是(例如):py:attr:
,而在从源代码记录时,你可以直接使用:attr:
。
当然,还有其他工具可以用来记录API。比如更经典的Doxygen,它使用\param
命令,但这些命令并不是专门为记录Python代码设计的,像Sphinx那样。
122
根据我的经验,numpy文档字符串规范(PEP257的扩展)是最常用的、被广泛遵循的规范,这些规范也得到了像Sphinx这样的工具的支持。
举个例子:
Parameters
----------
x : type
Description of parameter `x`.