I learned from a PR that the namedtuple attribute is automatically set to the docstring "Alias for field number xx".
$ python
Python 3.8.1 (default, Feb 13 2020, 13:34:23)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import namedtuple
>>>
>>> Coordinate = namedtuple('Coordinate', 'X Y')
>>> Coordinate.__doc__
'Coordinate(X, Y)'
>>> Coordinate.X.__doc__
'Alias for field number 0'
>>> Coordinate.Y.__doc__
'Alias for field number 1'
If you process this class with Sphinx (autodoc) and generate a document, the following document will be generated.
Although the amount of information is small, I have created a document that uses paper.
The workaround for this issue is the code introduced in Removing namedtuple docstrings for Sphinx. If you find the attribute of namedtuple, delete it. You can simplify redundant documents by including this [^ 1].
[^ 1]: On the other hand, this approach has the disadvantage that the mapping between the namedtuple position and the attribute name is difficult to understand because autodoc sorts the attributes alphabetically if nothing is specified. I'm a little confused about what to do with Sphinx itself.
Also, in How to write a docstring to create a namedtuple document with sphinx, the approach is to describe the document of each attribute with the docstring of the generated class. Introduced.
class NamedTupleWithDocstring2(namedtuple("NamedTuple", "aaa bbb ccc")):
"""
hogehoge
.. py:attribute:: aaa
Description of the ``aaa``.
.. py:attribute:: bbb
Description of the ``bbb``.
.. py:attribute:: ccc
Description of the ``ccc``.
"""
I see, you can insert any description in this case.
You can freely control the document in various ways of writing with docstring, but the code is verbose. If you have Python 3.6 or higher and Sphinx 2.4, it's a little simpler to write.
Using variable annotations introduced in Python 3.6, namedtuple and its documentation can be written as:
from typing import NamedTuple
class Coordinate(NamedTuple):
"""A 2-dimension coordinate."""
X: float #: the coordinate on X-axis
Y: float #: the coordinate on Y-axis
And if you use Sphinx 2.4, the #:
comment attached to this variable annotation will be interpreted as a docstring, so if you process the above code with Sphinx, it will be converted as follows.
Let's aim for smart code and smart documents with new features.
Recommended Posts