拿破仑和Autodoc如何与文件记录员互动

问题描述

我注意到Sphinx渲染类描述的行为发生了变化。有了这段代码

# my example happens to be a dataclass,but the behavior for 
# regular classes is the same
@dataclass
class TestClass:
    """This is a test class for dataclasses.

    This is the body of the docstring description.
    """
    var_int: int
    var_str: str

加上一些通用的Sphinx设置,大约两年前我曾经获得过

Documentation shows just the docstring

现在正在得到这个

Documentation shows class variables as if they were in the docstring

是否有一种方法告诉Sphinx不要将类变量添加类定义底部?仅仅因为它们没有认值,就假设它们的值为None尤其令人讨厌。


这个问题是在this post的讨论中提出的,在有关Sphinx配置等的评论中还包含了更多上下文。

解决方法

autodoc指令包含对象的成员,具体取决于:

  • 使用:members:选项(适用于具有文档字符串的成员)。
  • 使用了:undoc-members:选项(适用于没有文档字符串的成员)。

例如:

dc module
=========

.. autoclass:: dc.Foo

在上面的.rst文件中,autodoc指令未设置显式选项,Sphinx将执行的操作是隐式应用从conf.py中的autodoc_default_flags获取的选项标志。

conf.py中设置以下内容将导致Sphinx将对象的所有成员(带或不带文档字符串)包括在所有未明确指定选项的指令中。

# autodoc settings
autodoc_default_options = {
    'members':          True,'undoc-members':    True,}

结果:

enter image description here

但是,这引发了一个问题:如果{doc {1}} docstring section中明确指定了成员,而autodoc扩展中还包括了,则autodoc和sphinx-napoleon扩展会做什么? ?

文档字符串

Napoleon interprets every docstring that autodoc can find (...) Inside each docstring,specially formatted Sections are parsed and converted to reStructuredText

例如,将以下文档字符串与上面在Attributes中指定的选项一起使用。

autodoc_default_options

在这种情况下,成员将被声明两次,每次扩展都会声明一次,并且相应的reST声明将作为重复生成。重复的reST声明将导致通常的警告:

dc:Foo.var_a的C:\ dc.py:docstring:警告:dc.Foo.var_a的重复对象描述,dc中的其他实例,对其中一个使用:noindex:

C:\ dc.py:dc.Foo.var_b的文档字符串:1:警告:dc.Foo.var_b的重复对象说明,dc中的其他实例,对其中一个使用:noindex:

在这里可以注意到一个区别:狮身人面像-拿破仑将以其自己的docstring section声明该成员,而autodoc则将其正常呈现为其他成员。视觉差异将取决于主题,例如使用import dataclasses @dataclasses.dataclass class Foo: """Docstring for Foo Attributes: var_a (str): An integer. var_b (int): A string. """ var_a: str var_b: int 主题:

enter image description here

最后,如果您想使用狮身人面像-拿破仑docstring sections来记录成员,并在保留classic的同时避免autodoc重复reST声明,则可以在其中显式使用autodoc_default_options选项具体指令,例如:

:exclude-members:

仅使用sphinx-napoleon生成的reST指令记录成员:

enter image description here