如何在sphinx autodoc

时间:2016-09-19 04:06:05

标签: python python-sphinx

我正在使用Sphinx记录项目我想创建一个autoclass::指令的专用版本,允许我修改某些类的文档字符串。

我尝试了一件事:搜索sphinx源代码,我发现autoclass指令是通过ClassDocumenter object创建的。在此之后,我的想法是为感兴趣的类注册ClassDocumenter的子类,然后重写get_doc以修改文档字符串。

我尝试进行此类扩展:

from six import class_types
from sphinx.ext.autodoc import ClassDocumenter
from testmodule import Foo  # the class that needs modified documentation


class MyClassDocumenter(ClassDocumenter):
    objtype = 'myclass'
    priority = 20  # higher priority than ClassDocumenter

    @classmethod
    def can_document_member(cls, member, membername, isattr, parent):
        return isinstance(member, class_types) and issubclass(member, Foo)

    def get_doc(self, encoding=None, ignore=1):
        doc = super(MyClassDocumenter, self).get_doc(encoding, ignore)
        # do something to modify the output documentation
        doc[0].insert(0, "ADD SOMETHING TO THE DOC")
        return doc

def setup(app):
    app.add_autodocumenter(MyClassDocumenter)

问题是,当我运行这个时,我收到一个错误:ERROR: Unknown directive type "py:myclass".注册记录器似乎不足以注册相关指令,但是我还没有找到任何线索。狮身人面像的来源告诉我这样的注册应该如何发生。它不像使用标准add_directive()方法那么简单,因为我没有明确的注册指令。

如何在sphinx中正确完成自动记录程序的这种专业化?

(注意:重现错误的完整文件集可用in this gist

2 个答案:

答案 0 :(得分:0)

我在Docutils markup API

中找到了一些东西
  

指令由来自docutils.parsers.rst.Directive的类处理。它们必须使用Sphinx.add_directive()或Sphinx.add_directive_to_domain()通过扩展进行注册。

这是你在找什么?

答案 1 :(得分:0)

Binding类在适当时需要应用现有指令。这可以是“内置”指令,也可以是您创建和注册的自定义指令。无论哪种方式,要使用的指令都由BindableProperty class属性指定。您可以明确指定此值:

Documenter

或者,您似乎可以省略directivetype,默认情况下它将使用与class MyClassDocumenter(ClassDocumenter): directivetype = 'foo' # corresponds to :foo: in the doc source objtype = 'bar' priority = 20 相同的值。 (这是一个有根据的猜测)

那么问题是:您是否为directivetype注册了新指令?如果不是,我认为这是问题所在。或者,如果您想要使用其他指令(无论是内置指令还是自定义指令),答案可能是通过在objtype类定义中包含:myclass:的值来明确指定它。