Search code examples
pythonpython-sphinxmathjaxdocstringnumpydoc

Does \r stand for something in sphinx?


I'm writing my docstring following the numpy docstring guidelines. Then I use sphinx's autodoc to generate my documentation. Within some docstrings I'm using LaTeX formulas (sphinx.ext.mathjax). It seems that \r means something special like a new line. If I have the following command:

"""
This :math:`\langle a, b\rangle` denotes the dot product of a and b
"""

it doesn't properly render. It puts like angle to a new line and gives me an error: Inline interpreted text or phrase reference start-string without end-string If I replace the \rangle with \langle everything works fine. How can I fix this?


Solution

  • The solution is to escape with a double slash or place a "r" (without the quotes) in from of the triple quotes, this disables the interpretation of the slashes inside the quotes:

    r"""
    This :math:`\langle a, b\rangle` denotes the dot product of a and b
    """
    

    There are several prefixes that influence the definition of string literals, see the documentation of Python.

    Relevant excerpts:

    The backslash () character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

    and

    Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters. As a result, in string literals, '\U' and '\u' escapes in raw strings are not treated specially.