Search code examples
pythonpython-sphinxrestructuredtext

How to link to typecontextmanager label in Python 3 docs via sphinx


I am trying to put a reference to the following link into one of my reST documents: https://docs.python.org/3/library/stdtypes.html#typecontextmanager. I am trying to use a :ref: inline directive instead of a link.

I ran python -m sphinx.ext.intersphinx https://docs.python.org/3/objects.inv. The result shows, among other things:

...
std:label
    23acks                    Acknowledgements             : whatsnew/2.3.html#acks
    23section-other           Other Changes and Fixes      : whatsnew/2.3.html#section-other
...
    typebytearray             Bytearray Objects            : library/stdtypes.html#typebytearray
    typebytes                 Bytes Objects                : library/stdtypes.html#typebytes
    typecontextmanager        Context Manager Types        : library/stdtypes.html#typecontextmanager
    typeiter                  Iterator Types               : library/stdtypes.html#typeiter
    typememoryview            Memory Views                 : library/stdtypes.html#typememoryview
...

The bolded URL is exactly what I am looking for since my intersphinx_mapping looks like this:

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

I use the following directive:

:ref:`context manager <python:typecontextmanager>`

This seems to be pointing to the right label, but I get the following warning:

WARNING: undefined label: python:typecontextmanager (if the link has no caption the label must precede a section header)

The :ref: gets replaced by the string context manager, but there is no link.

What am I missing?

I am using sphinx 1.6.3 on an Anaconda install of Python 3.6.2

Note 1

I have the same problem using :ref:`with <python:with>`, which is supposed to point to https://docs.python.org/3/reference/compound_stmts.html#with, according to the inventory line (also under std:label):

     with                       The with statement          : reference/compound_stmts.html#with

I am guessing that a solution to the main question will most likely solve this as well.

Note 2

Probably not 100% relevant, but I can link to :py:meth:`~contextmanager.__enter__` in the same section without any problems.


Solution

  • Either of these work for me.

    :ref:`python:typecontextmanager`
    :ref:`typecontextmanager <python:typecontextmanager>`
    

    Note that if you use angle brackets around the target, then you must include a title.

    Here's how they render for me:

    As an aside, I recently added context managers to Pyramid's documentation in its Glossary, which I think does a good job of explaining what they are. Here's the reST source:

    :ref:`With Statement Context Managers <python:context-managers>`
    :ref:`with <python:with>`