[英]Python-Sphinx: “inherit” method documentation from superclass
編輯:截至目前(Sphinx 1.4.9),似乎無法告訴 Sphinx 做我想做的事(請參閱 GitHub 上的問題)。 Brecht Machiels 的公認答案以另一種方式解決了這個問題,直到 Sphinx 有一天能夠做到這一點。
描述:我正在嘗試使用 sphinx-apidoc 記錄一個 Python 項目。 Sphinx 配置幾乎是默認的,我只是包含了'sphinx.ext.autodoc'
。
它一般工作,但派生類不會像我期望的那樣繼承其超類的方法文檔。
示例:考慮一個名為project
的非常簡約的 Python 包。 除了一個空的__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:
在默認的index.rst
包含apidoc/modules.rst
后跟make html
為類及其方法生成基本的 html 文檔。 不幸的是, Derived.give
的文檔字符串是空的。
問題:有沒有辦法告訴 Sphinx 在沒有裝飾器魔法的情況下獲取父級的方法文檔,如這篇SO 帖子中所述,對於每個方法?
您可以通過為抽象基類使用元類來自動管理文檔字符串。 下面是這種元類的一個非常基本的實現。 它需要擴展以正確處理多個基類和極端情況。
# -*- 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()
時,這也將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.