12

I've been trying to figure out what's wrong with this expression in my docstring. I'm using the sphinx.ext.mathjax extension in python sphinx v1.2b. The docstring:

.. math::

    w_k^* = \min_{w_k} \ell_k(w_k) + \lambda\left(\alpha||w_k||_1 
    + \frac{1}{2}(1-\alpha) ||w_k||^2\right)

This is what appears: enter image description here

But it continues to generate this strange warning and not render the expression at all:

WARNING: Block quote ends without a blank line; unexpected unindent.

Strangely enough, if I remove \alpha, \left, \right, \frac symbols, the expression renders fine without warnings. Not sure why \lambda would be supported and not \alpha.

mzjn
  • 48,958
  • 13
  • 128
  • 248
bluecat
  • 401
  • 5
  • 11

1 Answers1

20

From the Sphinx documentation:

Keep in mind that when you put math markup in Python docstrings read by autodoc, you either have to double all backslashes, or use Python raw strings (r"raw").

This is needed so that LaTeX commands, such as \alpha, are interpreted correctly (\a and a few other sequences have special meaning in a string literal).

This is the raw version of the docstring in the question, with triple quotes, prepended by r:

r"""
.. math::
 
    w_k^* = \min_{w_k} \ell_k(w_k) + \lambda\left(\alpha||w_k||_1 
    + \frac{1}{2}(1-\alpha) ||w_k||^2\right)
"""
mzjn
  • 48,958
  • 13
  • 128
  • 248
  • Thanks this was indeed the problem. Should I always double all backslashes? I'm trying to follow the [numpy doscstring standard](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt). But they neither use raw strings or double backslashes. – bluecat May 09 '13 at 22:23
  • Not all LaTeX commands clash with Python's special escape sequences. You noted yourself that `\lambda` worked. So it is not strictly true that you **always** must double backslashes or use raw strings (but it seems like good practice to do so, to save yourself from trouble). – mzjn May 10 '13 at 08:47
  • I think it would be helpful to show the original equation: w_k^* = \min_{w_k} \ell_k(w_k) + \lambda\left(\alpha||w_k||_1 + \frac{1}{2}(1-\alpha) ||w_k||^2\right), and then show how it needs to be altered in order to have autodoc read it correctly inside of a Python docstring. – benjaminmgross Nov 15 '13 at 06:30
  • @Factor3: The equation does not need to be altered. All that is needed is an `r` in front of the docstring (to make the string "raw"). – mzjn Nov 15 '13 at 08:35
  • @mzjn, thanks. So to clarify, the function :math:'\sigma_t \triangleq X + Y' would likely not render inside a Python docstring, and should be written as :math:r'\sigma_t \triangleq X + Y', and will render in a Python docstring properly? – benjaminmgross Nov 19 '13 at 02:08
  • 1
    @Factor3: the `r` should come immediately before the string literal. Here is an example: http://stackoverflow.com/a/8386407/407651. – mzjn Nov 19 '13 at 09:43