在Python文档中使用javadoc
我现在刚开始学习Python,之前有很强的PHP背景。在PHP中,我习惯使用javadoc
作为文档模板。
我在想,javadoc
在Python中是否也适合用作docstring
文档。这里有什么既定的规范和官方指南吗?
比如说,像这样的文档是不是太复杂,不符合Python的思维方式,还是说我应该尽量简洁一些?
"""
replaces template place holder with values
@param string timestamp formatted date to display
@param string priority priority number
@param string priority_name priority name
@param string message message to display
@return string formatted string
"""
如果我写得太详细了,是不是应该用这样的方式(大部分文档不会通过__doc__
方法打印出来)?
# replaces template place holder with values
#
# @param string timestamp formatted date to display
# @param string priority priority number
# @param string priority_name priority name
# @param string message message to display
#
# @return string formatted string
def format(self, timestamp = '', priority = '', priority_name = '', message = ''):
"""
replaces template place holder with values
"""
values = {'%timestamp%' : timestamp,
'%priorityName%' : priority_name,
'%priority%' : priority,
'%message%' : message}
return self.__pattern.format(**values)
4 个回答
26
Python的文档字符串标准在Python增强提案257中有详细说明。
你可以为你的方法写一个这样的注释:
def format(...):
"""Return timestamp string with place holders replaced with values.
Keyword arguments:
timestamp -- the format string (default '')
priority -- priority number (default '')
priority_name -- priority name (default '')
message -- message to display (default '')
"""
79
请遵循Google Python 风格指南。注意,Sphinx 也可以使用Napolean这个扩展来解析这种格式,这个扩展会和 Sphinx 1.3 一起提供(它也兼容PEP257):
def func(arg1, arg2):
"""Summary line.
Extended description of function.
Args:
arg1 (int): Description of arg1
arg2 (str): Description of arg2
Returns:
bool: Description of return value
"""
return True
这个例子来自上面链接的 Napolean 文档。
关于所有类型的文档字符串的详细示例在这里。
233
你可以看看 reStructuredText(也叫“reST”)格式,这是一种纯文本/文档字符串的标记格式,可能是Python界最流行的格式。你还应该了解一下 Sphinx,这是一个可以从reStructuredText生成文档的工具(比如Python的官方文档就是用这个生成的)。Sphinx可以从你代码中的文档字符串提取文档(具体可以查看 sphinx.ext.autodoc),并且能够识别遵循特定规则的reST 字段列表。这可能已经成为(或正在成为)最流行的做法。
你的例子可能看起来像这样:
"""Replace template placeholder with values.
:param timestamp: formatted date to display
:param priority: priority number
:param priority_name: priority name
:param message: message to display
:returns: formatted string
"""
或者可以加上类型信息:
"""Replace template placeholder with values.
:param timestamp: formatted date to display
:type timestamp: str or unicode
:param priority: priority number
:type priority: str or unicode
:param priority_name: priority name
:type priority_name: str or unicode
:param message: message to display
:type message: str or unicode
:returns: formatted string
:rtype: str or unicode
"""