gpt4 book ai didi

python-sphinx - Sphinx 文档中的人类可读可迭代对象

转载 作者:行者123 更新时间:2023-12-04 09:42:52 27 4
gpt4 key购买 nike

Sphinx-autodoc 将字典、列表和元组扁平化 - 使长的几乎不可读。也并不总是需要 pretty-print 格式,因为一些嵌套的容器比分列更好地保持扁平化。有没有办法显示源代码中输入的可迭代对象?

最佳答案

直接从源代码获取,并添加 .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 和结果:

enter image description here

( :autodata: 与空 :annotation: 是排除原始扁平化字典)。

一些从 this answer 借来的代码.

关于python-sphinx - Sphinx 文档中的人类可读可迭代对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62253903/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com