使用类型注释记录类属性

40

我希望能够从文档字符串自动生成我的代码文档。我有一些基本的类用于存储一些数据:

class DataHolder:
    """
    Class to hold some data

    Attributes:
        batch: Run without GUI
        debug (bool): Show debug messages
    """
    batch: bool = False
    debug: bool = False
    name: str = 'default'
    """Object name"""
    version: int = 0
    """int: Object version"""

我的rst文件:

DataHolder
==========

.. autoclass:: data_holder.DataHolder
   :members:

我用了不同的方式记录下每个属性以展示它们的区别,以下是输出结果:
enter image description here

看起来Sphinx无法将Attributes部分与实际属性连接起来,这就是为什么它无法显示它们的默认值。

我想要实现的最终输出效果是像version字段那样,使用为batch定义的docstring。 我希望显示属性名称、默认值和类型,但从类型注释中提取。看起来Sphinx在这种情况下忽略了类型注释。

我的Sphinx扩展程序:

extensions = [
    'sphinx.ext.viewcode',
    'sphinx.ext.autodoc',
    'sphinxcontrib.napoleon',
]

我该怎么做才能实现这样的行为?我找不到任何关于这种用例的好例子。


你使用的Sphinx版本是什么?从1.3版本开始,Napoleon已经作为sphinx.ext.napoleon与Sphinx打包在一起。请参见https://pypi.org/project/sphinxcontrib-napoleon/。 - mzjn
我正在使用1.7版本,sphinx.ext.napoleon没有做出任何改变。 - Djent
你安装了"sphinxcontrib-napoleon"吗? - Jishnunand P K
很抱歉要传递这个坏消息,但是看着 napoleon 扩展的源代码,似乎这是不可能的。 - Jacques Gaudin
1
你可以尝试使用 .. autoattribute:: 吗?例如,可以参考这个答案 - DalyaG
":vartype:" 看起来在类型注释支持之前是您文档字符串中的一个不错的权宜之计。 - Matthew Story
3个回答

2

我认为您不能在docstring中放置属性部分来获得所需的结果。

我尝试为每个属性添加文档注释,并指定类型和所需的注释。

class DataHolder:
"""
Class to hold some data

Each attribute needs its own doc comment with its type
"""

#: bool: Run without Gui
batch = False

#: bool: Show debug messages
debug = False

#: str: Object Name
name = 'default'

#: int: Object Version
version = 0

这将产生以下输出和每个输出的良好类型描述。
看这里: 请看这里!

-2
class DataHolder:
    """
    Class to hold some data

    Attributes:
        batch: Run without GUI
        debug (bool): Show debug messages
        name: Object name
        version: Object version
    """
    batch: bool = False
    debug: bool = False
    name: str = 'default'
    version: int = 0
    # INLINE COMMENT for ONE line
    """
    DocString as inline-comment I havent seen that yet.
    """

12
解释你的答案比仅仅发布代码要好得多。这对未来的人们更有帮助,也更容易受到赞同。 - David Buck

-5

有一个内置库用于从 doc_strings 生成文档。

https://docs.python.org/2/library/pydoc.html

你所需要做的就是执行

$ pydoc <modulename>

它提供了一个美丽的文档列表,列出了doc_strings、定义的参数和返回值。试一试吧。

很遗憾,您的帖子并没有回答 OP 的问题。 - d1sh4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接