Python-Sphinx: inherit documentation from superclass

Edit: At the moment (Sphinx 1.4.9), there seems to be no way to tell the Sphinx to do what I want (see issue on GitHub). the accepted answer from Brecht Machiels solves the problem in a different way until the Sphinx can do it one day.

Description: I am trying to document a Python project using sphinx-apidoc. Sphinx configuration is almost the default, I just turned it on 'sphinx.ext.autodoc'.

It works in general, but derived classes do not inherit documentation by the method of their superclasses, as I would expect.

Example: Consider a very minimal Python package called project. In addition to the empty one, __init__.pyit consists of only one file ( base.py, see below)

# -*- coding: utf-8 -*
import abc


class Superclass(object):
    """The one to rule them all"""

    @abc.abstractmethod
    def give(self, ring):
        """Give out a ring"""
        pass


class Derived(Superclass):
    """Somebody has to do the work"""

    def give(self, ring):
        print("I pass the ring {} to you".format(ring))

Running sphinx-apidoc ( sphinx-apidoc -o apidoc project -f) generates the following files:

  • apidoc/modules.rst

    project
    =======
    
    .. toctree::
       :maxdepth: 4
    
       project
    
  • apidoc/project.rst

    project package
    ===============
    
    Submodules
    ----------
    
    project.base module
    -------------------
    
    .. automodule:: project.base
        :members:
        :undoc-members:
        :show-inheritance:
    
    
    Module contents
    ---------------
    
    .. automodule:: project
        :members:
        :undoc-members:
        :show-inheritance:
    

The apidoc/modules.rstdefault inclusion index.rstthat follows make htmlgenerates basic html documentation for both classes and their methods. Sorry, docstring is Derived.giveempty.

Question: Is there a way to tell Sphinx to take the documentation of the parent method without decorator magic, as described in this SO post for each individual method?

+4
source share
1 answer

docstrings , . . .

# -*- coding: utf-8 -*
import abc


class SuperclassMeta(type):
    def __new__(mcls, classname, bases, cls_dict):
        cls = super().__new__(mcls, classname, bases, cls_dict)
        for name, member in cls_dict.items():
            if not getattr(member, '__doc__'):
                member.__doc__ = getattr(bases[-1], name).__doc__
        return cls


class Superclass(object, metaclass=SuperclassMeta):
    """The one to rule them all"""

    @abc.abstractmethod
    def give(self, ring):
        """Give out a ring"""
        pass


class Derived(Superclass):
    """Somebody has to do the work"""

    def give(self, ring):
        print("I pass the ring {} to you".format(ring))

, Sphinx, help() .

+3

Source: https://habr.com/ru/post/1660297/


All Articles