【问题标题】:Sphinx: Link to a method of a class in another module in Python docstringSphinx:链接到 Python 文档字符串中另一个模块中的类的方法
【发布时间】:2017-07-24 13:45:58
【问题描述】:

我想在另一个模块的另一个方法(比如module_1.py)中添加一个链接到一个模块(比如module_2.py)中的一个类的方法。我希望该链接可以在 Sphinx 中使用。

假设:

module_1.py

class ABC:
   def foo(self):
      """
      See docstring of module_2.py bar():<link to bar() in module_2.py>
      """
      print("foo")

module_2.py

class XYZ:
    def bar(self):
    """
    This function prints hello.
    """
    print("hello")

【问题讨论】:

标签: python python-3.x python-sphinx docstring


【解决方案1】:

要真正获得超链接,您的方法引用需要包含完整路径。创建任何链接的最简单方法是使用 :obj: 交叉引用:

"""See docstring of :obj:`path.to.module_2.XYZ.bar`."""

查看path.to.module_2.XYZ.bar的文档字符串。

您可以使用tild ~ 将锚文本缩短到路径的最后一个元素:

"""See docstring of :obj:`~path.to.module_2.XYZ.bar`."""

查看bar的文档字符串。

或者像这样指定custom text

"""See docstring of :obj:`XYZ.bar <path.to.module_2.XYZ.bar>`."""

查看XYZ.bar的文档字符串。

这也许是对读者最友好的解决方案。

为了完整起见,请注意 :obj: 是一个通用的无类型引用,但 Sphinx 为 several other categories of cross-reference 提供了一些特定的行为。

【讨论】:

    【解决方案2】:

    你可以写:

    class ABC:
      def foo(self):
        """
        See docstring of :py:meth:`bar() <XYZ.bar>` in :py:mod:`module_2`.
        """
        print("foo")
    

    显示的标记使用 角色 链接到记录的元素。如果 Python 是您的文档的默认域,则可以省略 :py。角色meth 链接到方法名称。可以使用带点的名称。同样,mod 链接到模块名称。角色的内容写为wetween ``。内容(逻辑链接名称可以有不同的视觉内容。因此逻辑链接名称写成&lt;&gt;。例如::role:`text &lt;logical name&gt;`

    更多信息:http://www.sphinx-doc.org/en/stable/domains.html#role-py:meth

    【讨论】:

    • 我在它的文档字符串中看不到bar() 的路径。假设你禁止写in :py:mod:module_2``
    猜你喜欢
    • 2014-02-12
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    相关资源
    最近更新 更多