Python-Sphinx:从超类“继承”方法文档

2024-04-05

Edit:截至目前(Sphinx 1.4.9),似乎没有办法告诉 Sphinx 做我想做的事情(参见issue https://github.com/sphinx-doc/sphinx/issues/3140在 GitHub 上)。这接受的答案 https://stackoverflow.com/a/40613306/5682996布莱希特·马希尔斯(Brecht Machiels)以另一种方式解决了这个问题,直到有一天狮身人面像可能能够做到这一点。

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

它通常有效,但派生类不会像我期望的那样继承其超类的方法文档。

Example:考虑一个非常简约的 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))

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

  • 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:
    

包括apidoc/modules.rst在默认情况下index.rst其次是make html为类及其方法生成基本的 html 文档。不幸的是,文档字符串Derived.give是空的。

问题:有没有办法告诉 Sphinx 在没有装饰器魔法的情况下获取父级的方法文档,如中所述this https://stackoverflow.com/questions/13741998/is-there-a-way-to-let-classes-inherit-the-documentation-of-their-superclass-withSO 为每种方法发帖?


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

# -*- 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()在派生类上。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python-Sphinx:从超类“继承”方法文档 的相关文章

随机推荐