Python-Sphinx:来自超类的"继承"方法文档

Ale*_*exV 5 python python-sphinx

编辑: 截至目前(Sphinx 1.4.9)似乎没有办法告诉Sphinx做我想做的事(参见GitHub上的问题).该接受的答案,从布莱希特Machiels解决以其他方式问题,直到狮身人面像可能是能够做到一天.

描述: 我正在尝试使用sphinx-apidoc记录Python项目.Sphinx配置几乎是默认的,我只是包括在内'sphinx.ext.autodoc'.

它一般工作,但派生类不会像我期望的那样继承其超类的方法文档.

示例: 考虑一个非常简约的Python包project.除了空__init__.py,它只包含一个文件(base.py见下文)

# -*- 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))
Run Code Online (Sandbox Code Playgroud)

运行sphinx-apidoc(sphinx-apidoc -o apidoc project -f)会生成以下文件:

  • apidoc/modules.rst

    project
    =======
    
    .. toctree::
       :maxdepth: 4
    
       project
    
    Run Code Online (Sandbox Code Playgroud)
  • 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:
    
    Run Code Online (Sandbox Code Playgroud)

包括apidoc/modules.rst在默认值中,index.rst然后make html为类及其方法生成基本的html文档.不幸的是,docstring Derived.give是空的.

问: 有没有办法告诉狮身人面像在描述拿父母的方法的文档没有装饰魔术这个 SO张贴每个单独的方法?

Bre*_*els 7

您可以通过为抽象基类使用元类来自动管理文档字符串。下面是这种元类的一个非常基本的实现。它需要扩展以正确处理多个基类和极端情况。

# -*- 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))
Run Code Online (Sandbox Code Playgroud)

这甚至是比让 Sphinx 这样做更好的解决方案,因为这在调用help()派生类时也有效。