使用类型注释

时间:2018-05-26 19:03:22

标签: python python-3.6 python-sphinx autodoc sphinx-napoleon

我想从docstrings自动生成文档到我的代码。我有一些用于存储一些数据的基本类:

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字段的结果,其中docstring定义为batch。我想显示具有默认值和类型的属性名称,但是从类型注释中获取。看起来Sphinx在这种情况下忽略了类型注释。

我的狮身人面像扩展:

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

我可以做些什么来实现这种行为?我找不到这种用例的好例子。

3 个答案:

答案 0 :(得分:1)

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

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

您只需要执行

$ pydoc <modulename>

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

答案 1 :(得分:0)

class DataHolder:
    """
    Class to hold some data

    Attributes:
        batch: Run without GUI
        debug (bool): Show debug messages
        name: Object name
        int: 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.
    """

答案 2 :(得分:-1)

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"""
相关问题