代码之家  ›  专栏  ›  技术社区  ›  Mad Physicist

修改Sphinx中的数据表示

  •  1
  • Mad Physicist  · 技术社区  · 6 年前

    我有以下模块:

    """
    This is a test.
    """
    
    class Test(dict):
        """ Should always appear empty in the docs. """
        def __repr__(self): return '{}'
        def __str__(self): return '{}'
        def __format__(self, *args): return '{}'
    
    #: This is a dictionary that appears appears to be empty in the docs, but isn't
    #: really. Enjoy!
    test = Test()
    test['a'] = 1
    test['b'] = 2
    

    我用文档记录模块

    .. automodule:: test
       :members:
    

    一切都井然有序但是,当我看到 test.test ,我明白了

    test .test = {'a': 1, 'b': 2}

    sphinx autodoc如何获取数据对象的表示,以及如何重写它整个要点 Test 类将生成以下输出:

    test .test = {}

    2 回复  |  直到 6 年前
        1
  •  2
  •   mzjn    6 年前

    字典值在 object_description 此Python文件中的函数: https://github.com/sphinx-doc/sphinx/blob/master/sphinx/util/inspect.py . 函数提供“一个repr()实现,该实现返回可在reST上下文中使用的安全文本”。

    Sphinx创建的表示可以通过使用 autodata 指令与 annotation 选择。

    .. automodule:: test
       :members:
       :exclude-members: test
    
    .. autodata:: test.test
       :annotation: = {}
    
        2
  •  1
  •   Mad Physicist    6 年前

    基于 @mzjn's comment ,我想出了一个非常复杂的解决方案,实际上在我的特定情况下有效,但我不会向其他人推荐。

    诀窍在于 object_description 功能:

    if isinstance(object, dict):
        try:
            sorted_keys = sorted(object)
        except Exception:
            pass # Cannot sort dict keys, fall back to generic repr
        ...
    

    如果 sorted 失败,说明默认为 repr . 最简单的制作方法 排序的 失败就是让我上课 Test 不适合:

    def __iter__(self):
        raise TypeError('no!') 
    

    虽然这是非常不推荐的通用词典扩展,但它对我的 测试 类,并生成预期结果。