简体   繁体   中英

python-sphinx extension, how to get name of current object?

How to get the name of parent object in Python code for which is current documentation build for? I mean how to get name of class "ExampleCls0" in MyDirective.run()?

class ExampleCls0():
    """
    .. mydirect::

    """

Lets suppose that we have Spring directive called mydirect.

And it is correctly registered in Sphinx and documentation is build for python code.

class MyDirective(Directive):
    required_arguments = 0
    optional_arguments = 0
    has_content = True
    option_spec = {}

    def run(self):
        env = self.state.document.settings.env

def setup(app):
    app.add_directive('mydirect', MyDirective)

For build I am using:

from sphinx.cmdline import main as sphinx_main
from sphinx.ext.apidoc import main as apidoc_main

apidoc_main(["--module-first", "--force", "--full",
             "--output-dir", "doc/", "."])

sphinx_main(["-b", "html", "-E",
      "-c", pwd,
      "doc/",
      "doc_build/",
])

I do not know if name of the parent object can be accessed somewhere in Directive.run method, but I found out that it is possible to read the name later.

class SchematicLink(nodes.TextElement):

    @staticmethod
    def depart_html(self, node):
        self.depart_admonition(node)

    @staticmethod
    def visit_html(self, node):
        parentClsNode = node.parent.parent
        assert parentClsNode.attributes['objtype'] == 'class'
        assert parentClsNode.attributes['domain'] == 'py'
        sign = node.parent.parent.children[0]
        assert isinstance(sign, desc_signature)
        absoluteName = sign.attributes['ids'][0]
        print(absoluteName) # file0.ExampleCls0
        self.visit_admonition(node)


class MyDirective(Directive):
    required_arguments = 0
    optional_arguments = 0

    def run(self):
        schema_node = SchematicLink()
        self.state.nested_parse(self.content,
                                self.content_offset,
                                schema_node)
        return [schema_node]

def setup(app):
    app.add_node(SchematicLink,
                 html=(SchematicLink.visit_html,
                       SchematicLink.depart_html))
    app.add_directive('mydirect', MyDirective)

And this is probably good example how NOT to do it. Code reads id from label of class doc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM