Colons in restructuredText inline literal

goodmami Source

How can I make an inline literal with a colon in restructuredText?

I'm trying to document a Python function that returns a dictionary, e.g., something like:

def function(...):
    """
    ...
    Returns:
        A dictionary mapping ``{id: {role: value}}``
    """

But when I compile with Sphinx, it complains:

WARNING: Inline literal start-string without end-string.

The literal end-string is certainly there, and it doesn't seem to violate other formatting rules, but I cannot get it to render the literal correctly with the colons (the braces aren't an issue; one: two is also problematic inside an inline literal). Escaping doesn't help:

""" ``one\: two`` """   --> WARNING
""" ``one\\: two`` """  --> WARNING
r""" ``one\: two`` """  --> WARNING

The only thing that seems to work is a :code: role:

""" :code:`{one: {two: three}}` """  --> OK

Is this a limitation of Sphinx? Or a bug with docutils? Or is there a way to get colons inside inline literals?

pythonpython-sphinxrestructuredtextautodocdocutils

Answers

answered 4 months ago goodmami #1

This behavior is not due to an inherent limitation of Sphinx, restructuredText, or autodoc, but in fact a bug in the (current version of the) Napoleon extension for processing Google-style docstrings. Napoleon uses a regular expression to partition content on a colon, and it greedily consumes characters until it reaches the colon. The reason it works with the :code: role is that Napoleon detects those before partitioning, but it does not detect the inline formatting (note that the problem also occurs with other inline formatting patterns, such as *emphasis* or **strong**). One way to get around the bug, until it is fixed, is to place a colon before the inline literal:

def function(a, b):
    """Put *a* and *b* in a dictionary.

    Returns:
        dict: ``{a: b}``
    """
    return {a: b}

comments powered by Disqus