问题
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.
Does Sphinx provide tools to print out the value of individual source code variables
Is there any pretty printing available?
回答1:
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).
回答2:
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
来源:https://stackoverflow.com/questions/27875455/displaying-dictionary-data-in-sphinx-documentation