对于Python文档,有没有真正的替代方法来重构dtext?

2024-06-16 10:41:55 发布

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

我很快就要开始一个开源的Python项目了,我想提前决定如何编写docstring。显而易见的答案是在autodoc中使用structuredtext和Sphinx,因为我真的很喜欢在docstrings中正确地记录我的代码,然后让Sphinx为我自动构造一个API文档。

问题是它所使用的structuredtext语法-我认为在呈现之前它是完全不可读的。例如:

:param path: The path of the file to wrap
:type path: str
:param field_storage: The :class:`FileStorage` instance to wrap
:type field_storage: FileStorage
:param temporary: Whether or not to delete the file when the File instance
    is destructed
:type temporary: bool

你必须放慢速度,花一分钟从混乱的句法中找出任何意义。我更喜欢Google方式(Google Python Style Guide),与上述方式相对应的是:

Args:
    path (str): The path of the file to wrap
    field_storage (FileStorage): The FileStorage instance to wrap
    temporary (bool): Whether or not to delete the file when the File
        instance is destructed

好多了!但当然,狮身人面像将没有这些,并呈现所有的文字后“Args:”在一长行。

所以总结一下-在我用这个重构的文本语法来破坏我的代码库之前,我想知道除了编写我自己的API文档之外,是否还有其他真正的替代方法来使用它和Sphinx。例如,Sphinx是否有处理Google风格Guide的docstring风格的扩展?


Tags: thetopathinstancefieldparamtypesphinx
3条回答

我认为目前没有比编写python项目文档更好的东西了。

为了获得更清晰的docstring,我最喜欢的选择是将sphinx^{}一起使用。根据您的示例,这看起来像:

def foo(path, field_storage, temporary):
    """This is function foo

    Parameters
    ----------
    path : str
        The path of the file to wrap
    field_storage : :class:`FileStorage`
        The :class:`FileStorage` instance to wrap
    temporary : bool
        Whether or not to delete the file when the File instance
        is destructed

    Returns
    -------
    describe : type
        Explanation
    ...

    Examples
    --------
    These are written in doctest format, and should illustrate how to
    use the function.

    >>> a=[1,2,3]
    >>> print [x + 3 for x in a]
    [4, 5, 6]
    ...
    """

    pass

(一个完整的例子是Here), HTML输出看起来像this

我认为rst文件的结构更清晰,可读性更强。guide提供了更多信息和约定。numpydoc扩展也可以与autodoc一起使用。

我已经创建了一个Sphinx extension来解析Google风格和NumPy风格的docstring,并将它们转换为标准的structuredtext。

要使用它,只需安装它:

$ pip install sphinxcontrib-napoleon 

并在conf.py中启用它:

# conf.py

# Add autodoc and napoleon to the extensions list
extensions = ['sphinx.ext.autodoc', 'sphinxcontrib.napoleon']

更多关于拿破仑的文献。

我使用epydoc而不是狮身人面像,所以这个答案可能不适用。

您描述的用于记录方法和函数的structuredText语法并不是唯一可能的语法。到目前为止,我更喜欢使用consolidated definition list来描述参数,这与Google的方式非常相似:

:Parameters:
  path : str
     The path of the file to wrap
  field_storage: FileStorage
     The FileStorage instance to wrap
  temporary: bool
     Whether or not to delete the file when the File instance is destructed

如果sphix支持我会试试的。如果没有,你也可以考虑使用epydoc来解决这个问题(尽管现在还没有那么积极的维护)。

相关问题 更多 >