在 Sphinx 文档中显示字典数据

Displaying dictionary data in Sphinx documentation

我在 Python 项目源代码中有一本字典,它描述了默认配置值。字典很长。我希望在 Sphinx 文档中看到除 "View source" 之外的其他格式的字典,以便人们可以快速检查默认值。

当与 Sphinx autodoc 一起使用时,Sphinx 是否提供选项来将类似字典的变量格式化为人类可读的格式?我目前正在使用 .. automodule:: 转储整个模块,我在文档中将字典作为一个长字符串转储(没有换行符,漂亮的打印,任何东西),基本上不可读。

这可能不是最优雅的解决方案(编写一个正确的指令来输出一个漂亮的字典会更好),但现在这是可行的:

将给定 here 的自定义 exec 指令添加到您的 Sphinx .conf 文件,然后,在您要打印字典的 .rst 文件中,执行如下操作:

.. 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

这将在您的文档中的 JavaScript 代码块中打印出您的字典(我发现这是在文档中呈现字典的最佳方式)。

如果字典值不是像这样计算的并且人类可读

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

假设您在 fruit.py 中从第 15 行开始定义了上述字典

那么你可以这样做:

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

您将在文档上获得人类可读的价值+评论等

我需要一个答案,但不喜欢现有的答案,所以我把头撞在墙上,想出了一个不完美但可以接受的解决方案。

它使用 pprint.pformat 并直接生成节点,但我无法弄清楚如何生成包含交叉引用目标的完整标记,因为如果我使用 KeyError: 'objtype' 它会一直死掉试图添加外层,Sphinx 文档没有任何帮助,相关的 Sphinx 扩展是迷宫般的。

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)

以下是我的使用方法:

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

----

.. pprint:: quicktile.__main__.DEFAULTS

DEFAULTS 是一个字典,用于在找到 none 时创建具有默认值的配置文件。)

...这是它的样子:

你们我都做到了,但你不会相信我,因为它实际上是五行导入。在回复中激怒我,但这已经工作了一两个星期而且我没有注意到它破坏了任何东西。

这是在 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

这需要你~呃哦~

变成~嗯嗯~

编辑:修复图像 b/c 获得了 ~rep~ 足以拥有它们

基于

此解决方案没有尾随括号。

将给定 here 的自定义 exec 指令添加到您的 Sphinx .conf 文件,然后,在您要打印字典的 .rst 文件中,执行 RST 中演示的类似操作 下面的部分。

textwrap.indent用于根据需要缩进字典内容

data = pad + 'STYLE_PARTS = ' + data.lstrip() 此行从数据的开头去除填充。请参阅下面 OUTPUT 的第一行。

另请参阅:

使用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)

输出

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"
}