我如何 link 到使用 Sphinx 的 str 方法?

How do I link to str methods using Sphinx?

我正在使用 Sphinx 从我的文档字符串生成我的 HTML 文档,就像一个很好的 lil' Pythonista。

我有一个如下所示的文档字符串:

def do_a_thing(text):
    '''
    Call the ``str.strip()`` method on ``text``. Then do something
    else with it.
    '''

但是,我希望它 link 到 https://docs.python.org/3/library/stdtypes.html#str.strip 而不是全部等宽和代码块。

我尝试了几种方法:

:py:func:`str.strip()`
:mod:`str.strip()`
:class:`str.strip()`
:any:`str.strip()`
:doc:`str.strip()`

None 这些工作 - 或者更准确地说,前四种方法给我一个等宽和粗体字体,但 none 实际上 link 任何地方。 any 指令给了我 WARNING: 'any' reference target not found: str.strip()

显然我可以自己制作一个 link,但这看起来很恶心,而且可能也不是我想要的,因为当我升级到 Python 4 时呢?然后我必须更新文档中的所有 links,这太恶心了。

link 到 str 方法的 Python 文档的正确方法是什么?

Intersphinx好吧!

conf.py中添加几行。金字塔文档有很好的例子来添加 Intersphinx extension and configuring intersphinx mappings.

extensions = [
    # ...
    'sphinx.ext.intersphinx',
    # ...
    ]

intersphinx_mapping = {
    #...
    'python': ('https://docs.python.org/3', None),
    #...
}

然后在您的 .rst 文件中,有几种方法可以指向 Python 文档。我们更喜欢使用以下格式,它向文档作者表明 link 将解析为指定的外部文档源。

:mod:`venv module <python:venv>`
:ref:`package <python:tut-packages>`

对于 Python,您还可以使用 Python Domain 中的任何指令,包括:

:py:meth:`str.strip`

就版本控制而言,您可以在 intersphinx 映射中使用多个名称或更新目标映射。

intersphinx_mapping = {
    #...
    'python2': ('https://docs.python.org/2', None),
    'python': ('https://docs.python.org/3', None),  # use "python" for default version
    #...
}

或将来...

intersphinx_mapping = {
    #...
    'python2': ('https://docs.python.org/2', None),
    'python3': ('https://docs.python.org/3', None),
    'python': ('https://docs.python.org/4', None),  # use "python" for default version
    #...
}