Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83438

Displaying dictionary data in Sphinx documentation

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 documentation in other format besides "View source", so that people can quickly check for the default values.

Does Sphinx provide options to format dictionary-like variables for human-readable format when used with Sphinx autodoc? I am currently using .. automodule:: to dump out the whole module and I get the dictionary as one long string dump in the documentation (no newlines, pretty printing, anything), being basically unreadable.

Upvotes: 19

Views: 6429

Answers (5)

Amour Spirit
Amour Spirit

Reputation: 197

Building on Erve1879 post

There are no trailing brackets with this solution.

Add the custom exec directive given here to your Sphinx .conf file, then, in the .rst file you want to print the dictionary, do something like is demonstrated in the RST section below.

textwrap.indent is used to indent the dictionary content as required.

data = pad + 'STYLE_PARTS = ' + data.lstrip() this line strips padding from the start of data. See first line of OUTPUT below.

See Also:

Using textwrap

RST


config
======

.. automodule:: config
    :members:
    :exclude-members: STYLE_PARTS

    .. exec::

        import json
        import textwrap
        from config import STYLE_PARTS
        pad = '    '
        cb = '.. code-block:: python\n\n'
        data = json.dumps(STYLE_PARTS, sort_keys=True, indent=4)
        data = textwrap.indent(text=data, prefix=pad)
        data = pad + 'STYLE_PARTS = ' + data.lstrip()
        cb = cb + data
        print(cb)

OUTPUT

STYLE_PARTS = {
    "0": "00",
    "1": "01",
    "2": "02",
    "3": "03",
    "4": "04",
    "5": "05",
    "6": "06",
    "7": "07",
    "8": "08",
    "9": "09",
    "bold": "BOLD",
    "continuance": "CONTINUANCE",
    "contract": "CONTRACT"
}

Upvotes: 1

sneakers-the-rat
sneakers-the-rat

Reputation: 106

y'all i have done it but you are not going to believe me because it is literally five lines with imports. roast me in the replies but this has been working for a week or two and i haven't noticed it breaking anything.

This is in conf.py :

from pprint import pformat
def object_description(object) -> str:
    return pformat(object, indent=4)

from sphinx.util import inspect
inspect.object_description = object_description

this takes yer ~uh oh~

image of sphinx docs without pretty formatting

into a ~uh huh~

image of sphinx docs with pretty formatting

edit: fixed images b/c got the ~rep~ enough to have them

Upvotes: 5

ssokolow
ssokolow

Reputation: 15345

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:

enter image description here

Upvotes: 5

naoko
naoko

Reputation: 5216

If dictionary value is not computed and human readable like this

FRUITS = {
   "Apple": "Red and Delicious",
   # note: eating too much orange make your hands orange
   "Orange": "A lot of vitamin C"
}

say you have the above dict defined in fruit.py starting from line#15

then you can do:

.. literalinclude:: ../path-to-file/fruit.py
   :language: python
   :lines: 15-
   :linenos:

and you will the Human readable value + comments etc right on doc

Upvotes: 7

Erve1879
Erve1879

Reputation: 845

This may not be the most elegant solution (it would be much better to write a proper directive to output a pretty-printed dictionary), but this works for now:

Add the custom exec directive given here to your Sphinx .conf file, then, in the .rst file you want to print the dictionary, do something like this:

.. exec::
    import json
    from some_module import some_dictionary
    json_obj = json.dumps(some_dictionary, sort_keys=True, indent=4)
    print '.. code-block:: JavaScript\n\n    %s\n\n' % json_obj

That will print out your dictionary in a JavaScript code block in your docs (which I find to be the best way to render dictionaries in the docs).

Upvotes: 9

Related Questions