gpt4 book ai didi

python - napoleon 和 autodoc 如何交互记录成员

转载 作者:行者123 更新时间:2023-12-02 02:34:06 24 4
gpt4 key购买 nike

我注意到 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 将隐式应用从 autodoc_default_flags 中获取的选项标志。在 conf.py 中。

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

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

结果:

enter image description here

但是,这提出了一个问题:如果成员在Attributes 中明确指定,autodoc 和 sphinx-napoleon 扩展会做什么 docstring section 但也包含在 autodoc 扩展中?

Docstrings

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

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

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

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

C:\dc.py:docstring of dc.Foo.var_a:1: WARNING: duplicate object description of dc.Foo.var_a, other instance in dc, use :noindex: for one of them

C:\dc.py:docstring of dc.Foo.var_b:1: WARNING: duplicate object description of dc.Foo.var_b, other instance in dc, use :noindex: for one of them

这里有一个不同之处:sphinx-napoleon 将在自己的 docstring section 中声明成员而 autodoc 会像其他成员一样正常呈现它。视觉差异将取决于主题,例如使用 classic 主题:

enter image description here

最后,如果您想使用 sphinx-napoleon 记录成员 docstring sections并避免来自 autodoc 的重复 reST 声明,同时保持 autodoc_default_options 如图所示,您可以在该特定指令中显式使用 :exclude-members: 选项,例如:

dc module
=========

.. autoclass:: dc.Foo
:exclude-members: var_a, var_b

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

enter image description here

关于python - napoleon 和 autodoc 如何交互记录成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64588821/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com