使用 :ref: 在 Python 文档字符串中使用 Sphinx

using :ref: in Python docstrings using Sphinx

我正在使用 Sphinx 来记录一个 python 项目,并且我正在尝试创建一个可重复使用的技巧以在多个位置使用。

通常,我会在 python 文件中使用以下语法:

"""
.. tip::
    I want this tip to be used in several locations. Why?
        - Save time
        - Work less
"""

现在无论我把它放在文件的开头,class 定义的正下方还是函数定义的正下方,这都有效。

我找到 Sphinx's manual for :ref:,建议使用标签:

.. _my_reusable_tip:

.. tip::
   ...

然后在我想要的任何地方用 :ref:`my_reusable_tip` 调用这个技巧。 手册指出 'it works across files, when section headings are changed, and for all builders that support cross-references'

问题是,无论我在项目中的哪个 .py 文件中编写标签和提示定义,:ref:`my_reusable_tip` 只显示 'my_reusable_tip',而不是提示本身。

我用来构建文档的是

sphinx-apidoc -f -F -o
make html

我很确定我的逻辑在某些方面有缺陷,但我不明白为什么。 我知道 Sphinx 在项目中搜索 reStructuredText 并在可能的情况下呈现它,但我想我在这里遗漏了一些东西。

我在这里错过了什么?

Python 3.4.3 顺便说一句。

在 sphinx 中,:ref: 只是一种更强大的链接(或引用)文档另一部分的方式。因此,您使用 :ref: 只会提供指向标签的超链接。

这不是替换或扩展块的方法。

Inline substitutions 可以使用 |...|,但是内联替换不能用于替换您似乎需要的块。

RestructuredText 不是模板语言,因此不提供类似宏的功能。如果您需要它,另一种解决方案是使用模板库,例如 makojinja 来处理此类问题。

只使用 reStructuredText 指令

.. include:: ./my_reusable_tip.txt

在您的第一个文件中?