Search code examples
pythonpython-sphinxrestructuredtext

Sphinx: Document an attribute that is same as a parameter


I want to document something like this with numpy style docstring.

class X(object):
    """ X

    Marble Counter

    Parameters
    ----------
    n_marbles : int
        an indicator of degree of madness

    Attributes
    ----------
    n_marbles : int
        an indicator of degree of madness
    """
    def __init__(n_marbles):
        self.n_marbles = n_marbles

The attribute and parameters are the same. Can/should I avoid repeating?


Solution

  • For a case like yours, where the input parameter and attribute are the exact same reference, I would only document the attribute. Anyone familiar with Python will immediately know that the parameter is.

    For more complex cases, I prefer to document both the class itself and the __init__ method. The parameter description would go into the docstring of __init__ in this case.

    Since you appear to be using the autodoc extension, you would need to add a :special-members: __init__ option to your autoclass directive. If you want to document other special members, you can add them to the parameter list of the option. You can also omit arguments to :special-members: entirely to document all magic attributes, but that may include things you don't want, like __weakref__.