问题描述
我注意到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不要将类变量添加到类定义的底部?仅仅因为它们没有默认值,就假设它们的值为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,}
结果:
但是,这引发了一个问题:如果{doc {1}} docstring section中明确指定了成员,而autodoc扩展中还包括了,则autodoc和sphinx-napoleon扩展会做什么? ?
文档字符串
例如,将以下文档字符串与上面在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
主题:
最后,如果您想使用狮身人面像-拿破仑docstring sections来记录成员,并在保留classic
的同时避免autodoc重复reST声明,则可以在其中显式使用autodoc_default_options
选项具体指令,例如:
:exclude-members:
仅使用sphinx-napoleon生成的reST指令记录成员: