将javadoc用于Python文档

2024-06-09 23:00:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在是从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)

Tags: toname文档messagestringparamdisplayplace
3条回答

python文档字符串的标准在Python Enhancement Proposal 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 '')
    """

跟随Google Python Style Guide。请注意,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文档的示例。

关于所有类型的docstringhere的综合示例。

看看reStructuredText(也称为“reST”)格式,它是纯文本/docstring标记格式,可能是Python世界中最流行的格式。您当然应该看看Sphinx,这是一个从structuredtext生成文档的工具(用于Python文档本身)。Sphinx包含从代码中的docstring提取文档的可能性(请参见sphinx.ext.autodoc),并根据某些约定识别reSTfield lists。这可能已经成为(或正在成为)最流行的方法。

您的示例如下所示:

"""Replaces 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
"""

或扩展类型信息:

"""Replaces 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
"""

相关问题 更多 >