Dori
Dori

Reputation: 1055

Why isn't Sphinx showing inherited members?

I have a base class Base and a derived class Derived. Using Sphinx, I want the class attributes of Base to appear in the documentation of Derived; I thought :inherited-members: would do the trick, but I'm having no luck so far.

Note that unlike this question, the members I need to document do not appear hard-coded in the class, only in the class docstring.

Minimal working example: under tmp/, I have the file a.py:

class Base:
    """
    :param x: X
    :type x: int
    """
    x = 1


class Derived(Base):
    """
    :param y: Y
    :type y: int
    """
    y = 2

the file index.rst:

Tmp
===

.. autoclass:: tmp.a.Base
    :members:

.. autoclass:: tmp.a.Derived
    :show-inheritance:
    :inherited-members:
    :members:

and conf.py, which only contains extensions = ['sphinx.ext.autodoc']. If I run the command

python -m sphinx.cmd.build . ./tmphtml/

then the output tmphtml/index.html shows this:

enter image description here

How can I get x to appear under the Parameters part of Derived? My current version of Sphinx is 3.3.1.

Upvotes: 0

Views: 1533

Answers (1)

Kale Kundert
Kale Kundert

Reputation: 1494

I think this might be a bug in Sphinx, but there's also a mistake in your example.

Your mistake is that you didn't document the x or y class attributes correctly. The :param: role is meant for describing function arguments, so Sphinx doesn't associate the x and y parameters with the class attributes of the same names. And then since Sphinx considers the class attributes undocumented, it doesn't include them in the documentation. Here is how the attributes should be documented:

class Base:
    x = 1
    """Spam"""

class Derived(Base):
    y = 2
    """Eggs"""

The (possible) bug is that even when you do this, Sphinx still considers the attributes undocumented. I think this is probably a consequence of attributes not having true docstrings, which forces Sphinx to do some tricks behind the scenes to make it seems like they do, but I'm not really sure. In any case, you can work around this behavior by including :undoc-members: in the .. autoclass:: directive. This will of course include every undocumented method/attribute in the documentation, but I couldn't figure out a way around this.

An alternative worth mentioning is a plugin I wrote called autoclasstoc. This is basically an easy way to have the documentation for Derived include links to the documentation for both x and y. The y documentation would actually be on the same page, since it's part of the Derived class, while the x documentation would be on the Base page. There'd also be nicely organized links for every method (including inherited ones). This doesn't exactly answer your question, but I think it gets at the same idea.

Upvotes: 1

Related Questions