Displaying dictionary data in Sphinx documentation

后端 未结 4 523
感动是毒
感动是毒 2020-12-10 13:15

I have a dictionary in Python project source code which describes default configuration values. The dictionary is quite lengthy. I\'d like to see dictionary in Sphinx docume

4条回答
  •  北海茫月
    2020-12-10 13:32

    I needed an answer to this but didn't like the existing answers, so I bashed my head against the wall for a bit and came up with an imperfect but acceptable solution.

    It uses pprint.pformat and generates the nodes directly, but I couldn't figure out how to generate the full markup including a cross-reference target because it would keep dying with KeyError: 'objtype' if I tried to add the outer layers, the Sphinx documentation wasn't any help, and the relevant Sphinx extensions are labyrinthine.

    from importlib import import_module
    from pprint import pformat
    from docutils.parsers.rst import Directive
    from docutils import nodes
    from sphinx import addnodes
    
    class PrettyPrintDirective(Directive):
        """Render a constant using pprint.pformat and insert into the document"""
        required_arguments = 1
    
        def run(self):
            module_path, member_name = self.arguments[0].rsplit('.', 1)
    
            member_data = getattr(import_module(module_path), member_name)
            code = pformat(member_data, 2, width=68)
    
            literal = nodes.literal_block(code, code)
            literal['language'] = 'python'
    
            return [
                    addnodes.desc_name(text=member_name),
                    addnodes.desc_content('', literal)
            ]
    
    
    def setup(app):
        app.add_directive('pprint', PrettyPrintDirective)
    

    Here's how I'm using it:

    .. automodule:: quicktile.__main__
       :members:
       :exclude-members: XDG_CONFIG_DIR,DEFAULTS,CfgDict
    
    ----
    
    .. pprint:: quicktile.__main__.DEFAULTS
    

    (DEFAULTS being a dict that's used to create a configuration file with default values if none is found.)

    ...and here's how it looks:

提交回复
热议问题