Search code examples
pythonparent-childpython-sphinxdocstringcross-reference

How to refer child class attributes in the parent class docstring?


I'm using :inherited-members: to show parent methods.

In the documentation generated for the child, is it possible to refer to the child class?

class Parent:
   """This is a {Child class name} class

   This is in the {Child group attribute} group
   """
   group = ''
   ...

class Child(Parent):
   group = 'TheChild'
   ...

In the generated documentation for the child, I would like to see:

> class Child(Parent)
>   Bases: Parent
>   This is a Child class.
>   It is in the TheChild group

Is this possible with Sphinx?


Solution

  • You can use the Sphinx Cross-referencing syntax inside the docstrings, with the appropriate roles from the Python domain. After that the autodoc directives in your .rst take care of the rest.

    Example parent_child.py

    class Parent:
        """
        This is a :py:class:`Child` class.
    
        This is in the :py:data:`Child.group` attribute.
        """
        group = 'TheParent'
    
    
    class Child(Parent):
        group = 'TheChild'
    

    parent_child.rst

    Parent\_Child
    =============
    
    .. autoclass:: parent_child.Parent
        :members:
        :undoc-members:
        :show-inheritance:
    
    .. autoclass:: parent_child.Child
        :members:
        :undoc-members:
        :show-inheritance:
    

    And the result:

    parent_child_image