【问题标题】:Human readable iterables in Sphinx documentationSphinx 文档中的人类可读迭代
【发布时间】:2020-09-26 22:28:33
【问题描述】:

Sphinx-autodoc 将 dicts、lists 和 tuples 扁平化 - 使得长的难以阅读。也不总是需要漂亮的打印格式,因为一些嵌套容器最好保持扁平而不是柱状。有没有办法在源代码中显示可迭代对象按类型输入

【问题讨论】:

    标签: python-sphinx restructuredtext autodoc


    【解决方案1】:

    直接从源代码获取,并为其添加.rst 命令:

    # conf.py
    from importlib import import_module
    from docutils  import nodes
    from sphinx    import addnodes
    from inspect   import getsource
    from docutils.parsers.rst import Directive
    
    class PrettyPrintIterable(Directive):
        required_arguments = 1
    
        def run(self):
            def _get_iter_source(src, varname):
                # 1. identifies target iterable by variable name, (cannot be spaced)
                # 2. determines iter source code start & end by tracking brackets
                # 3. returns source code between found start & end
                start = end = None
                open_brackets = closed_brackets = 0
                for i, line in enumerate(src):
                    if line.startswith(varname):
                        if start is None:
                            start = i
                    if start is not None:
                        open_brackets   += sum(line.count(b) for b in "([{")
                        closed_brackets += sum(line.count(b) for b in ")]}")
    
                    if open_brackets > 0 and (open_brackets - closed_brackets == 0):
                        end = i + 1
                        break
                return '\n'.join(src[start:end])
    
            module_path, member_name = self.arguments[0].rsplit('.', 1)
            src = getsource(import_module(module_path)).split('\n')
            code = _get_iter_source(src, member_name)
    
            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', PrettyPrintIterable)
    

    示例 .rst 和结果:

    :autodata: 与空的:annotation: 是为了排除原来的扁平化字典)。

    this answer借来的一些代码。

    【讨论】:

    • 提示:对模块名称使用内联文字以避免转义。使用双反引号将其包围(SO 中的 cmets 不允许显示反引号)。
    • @StevePiercy 实际上它使模块名称呈现为内联代码,这是不希望的
    • 如果外观不是您想要的,您可以自定义 CSS。不过,HTML 标记是正确的,因为它是标题中的内联文字。
    猜你喜欢
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    相关资源
    最近更新 更多