gpt4 book ai didi

python - 如何将对象添加到 Sphinx 的全局索引,或通过别名进行交叉引用?

转载 作者:行者123 更新时间:2023-12-04 02:35:11 26 4
gpt4 key购买 nike

每次我不得不引用一个方法时,我宁愿不:func:`package.subpackage.module.method`,尤其是对于经常使用的方法。有没有办法以某种方式“注册” package.subpackage 以便只有 module.method 就足够了? (更好的是,package.subpackage.module,所以 method 就足够了,假设没有冲突)。

解决方案不应涉及将目录添加到 packagesubpackage,但我可以将任何内容添加到 docs/。请注意,这里的问题涉及在文档字符串模块之外定义的 method(否则 .method 有效)。

最佳答案

您可以添加一个简单的扩展来解析您定义的别名。下面的例子是一个简短的概念证明:

# add this to conf.py

from sphinx.addnodes import pending_xref
from sphinx.ext.intersphinx import missing_reference
from docutils.nodes import Text

# alias ref is mapped to a pair (real ref, text to render)
reftarget_aliases = {
'foo.spam': ('foo.bar.baz.spam', 'spam'),
}


def resolve_intersphinx_aliases(app, env, node, contnode):
alias = node.get('reftarget', None)
if alias is not None and alias in reftarget_aliases:
real_ref, text_to_render = reftarget_aliases[alias]
# this will resolve the ref
node['reftarget'] = real_ref

# this will rewrite the rendered text:
# find the text node child
text_node = next(iter(contnode.traverse(lambda n: n.tagname == '#text')))
# remove the old text node, add new text node with custom text
text_node.parent.replace(text_node, Text(text_to_render, ''))

# delegate all the rest of dull work to intersphinx
return missing_reference(app, env, node, contnode)


def resolve_internal_aliases(app, doctree):
pending_xrefs = doctree.traverse(condition=pending_xref)
for node in pending_xrefs:
alias = node.get('reftarget', None)
if alias is not None and alias in reftarget_aliases:
real_ref, text_to_render = reftarget_aliases[alias]
# this will resolve the ref
node['reftarget'] = real_ref

# this will rewrite the rendered text:
# find the text node child
text_node = next(iter(node.traverse(lambda n: n.tagname == '#text')))
# remove the old text node, add new text node with custom text
text_node.parent.replace(text_node, Text(text_to_render, ''))


def setup(app):
app.connect('doctree-read', resolve_internal_aliases)
app.connect('missing-reference', resolve_intersphinx_aliases)

现在所有引用 :role:`foo.spam`将替换为 :role:`spam <foo.bar.baz.spam>` ,无论确切的角色是什么( classfuncmod 等等)。当然,这只是草稿且未经测试,但您应该明白了。甚至可能是新 Sphinx 扩展项目的一个很好的起点:-)

关于python - 如何将对象添加到 Sphinx 的全局索引,或通过别名进行交叉引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62293058/

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