Should Sphinx be able to document instance attributes in a class?

Viewed 6203

I'm finding conflicting and often dated information so hoping someone can clear this up.

I'd like to document something like this using Sphinx:

class MyClass:
    """
    MyClass, which is documented with a docstring at the class level
    """
    classVar = None
    """A class var with an initial value and a 1-line doc"""

    def __init__(self):
        """
        __init__'s docs
        """
        instanceVar1 = 10
        """An instance var with an initial val and 1-line doc"""

        #: An instance var with an initial val and a doc-comment
        instanceVar2 = 10

In my docs, I'd like to see instanceVar1 and its docstring (ideally with its default value, but I'd be happy with just the description). But if I run with an rst file of:

.. automodule:: mymodule.mycode
   :members:

I only see the class attributes, not the instance attributes: Image showing docs

Googling gives me conflicting info on what should/shouldn't work. Several older stack overflow chains cite issues with autodocumentation for instance attributes (such as here) but they also refer to it working if you've added docstrings like I've done above. Sphinx docs cite that all attributes can be autodocumented.

Can anyone comment on whether what I'm trying to do should work/it works for them now you/suggestions on what I might have messed up? Thanks.

1 Answers

Yes, what you did should work, and it — eventually — worked for me.

To demonstrate, I'm using the example from the Sphinx docs that you cited:

class Foo:
    """Docstring for class Foo."""

    #: Doc comment for class attribute Foo.bar.
    #: It can have multiple lines.
    bar = 1

    flox = 1.5   #: Doc comment for Foo.flox. One line only.

    baz = 2
    """Docstring for class attribute Foo.baz."""

    def __init__(self):
        #: Doc comment for instance attribute qux.
        self.qux = 3

        self.spam = 4
        """Docstring for instance attribute spam."""

I saved that as module.py and created the following index.rst:

.. automodule:: module

Along with this Sphinx configuration file, conf.py:

import sys
sys.path.insert(0, '.')
extensions = ['sphinx.ext.autodoc']
autodoc_default_options = {
    'members':         True,
    'member-order':    'bysource',
    'special-members': '__init__',
}

With all three files stored in the same folder, I ran Sphinx (2.1.1) via sphinx-build . ./html (on Python 3.7.3 and Windows 10) to render it as HTML: rendered HTML

As to what you "might have messed up"… Um, that's adequately put, as I'm sure you'll agree. ;-) It took me quite a while to realize this when, at first, I tried the same as above, but with the code example you provided: Your two alleged instance attributes, instanceVar1 and instanceVar2, are missing the self identifier in front. Oops. That's why it didn't work.

Related