Members of an object are included by an autodoc directive depending if:
- the
:members:
option is used (for members with docstrings).
- the
:undoc-members:
option is used (for members without docstrings).
For example:
dc module
=========
.. autoclass:: dc.Foo
In the above .rst
file the autodoc directive does not have explicit options set, what Sphinx will do is implicitly apply the option flags taken from the autodoc_default_flags
in conf.py
.
Setting the following in conf.py
would cause all members of an object (with or without docstrings) to be included by Sphinx in all directives that do not explicitly specify options.
# autodoc settings
autodoc_default_options = {
'members': True,
'undoc-members': True,
}
The result:
However, this raises a question: What do autodoc and sphinx-napoleon extensions do if members are explicitly specified in the Attributes
docstring section but also included by the autodoc extension?
Docstrings
Napoleon interprets every docstring that autodoc can find (...) Inside each docstring, specially formatted Sections are parsed and converted to reStructuredText.
For example, using the following docstring together with the options specified above in 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
In this case members will be declared twice, once by each extension, with the corresponding reST declaration being generated as a duplicate. Having a duplicate reST declaration will lead to the usual warning:
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
Here one difference can be noted: sphinx-napoleon will declare the member in its own docstring section whereas autodoc will render it normally as other members. The visual difference will depend on theme, for example using classic
theme:
Finally, if you want to document members using sphinx-napoleon docstring sections and avoid a duplicate reST declaration from autodoc while keeping autodoc_default_options
as shown, you can explicitly use :exclude-members:
option in that specific directive, for example:
dc module
=========
.. autoclass:: dc.Foo
:exclude-members: var_a, var_b
Would document the members using only sphinx-napoleon generated reST directives: