Search code examples
pythonhtmlrestructuredtextdocstringdocutils

Convert scipy docstrings (reST) to HTML using docutils


I'm designing a filter design GUI and would like to display docstrings from Python's scipy.signal in a QTextBrowser, requiring HTML format. I think docutils should do the job for me and I tried

from docutils.core import publish_string
from scipy.signal import remez
self.txtFiltInfoBox.append(publish_string(remez.__doc__,
          writer_name='html'))

where txtFiltInfoBox is a QTextBrowser instance. However, publish_string chokes on the first heading ("Parameters") it encounters in the docstring:

docutils.utils.SystemMessage: <string>:10: (SEVERE/4) Unexpected section title.

Parameters
----------

I think the reason is that the method's whole docstring is indented, leading to an invalid reST markup. Is there an easy way to dedent the docstring or to tell publish_string to ignore a certain number of leading blanks?

The full code can be found at pyFDA project.


Solution

  • You can use textwrap.dedent to, as the docs put it:

    Remove any common leading whitespace from every line in text.

    For example (from a similar question on CodeReview):

    >>> import textwrap
    >>> print(textwrap.dedent(
            """
            Usage examples:
            Test deployment:
                $ fab [noinput] test deploy
            Staging deployment:
                $ fab [noinput] staging deploy
            Production deployment:
                $ fab [noinput] production deploy
            """
    ))
    
    Usage examples:
    Test deployment:
        $ fab [noinput] test deploy
    Staging deployment:
        $ fab [noinput] staging deploy
    Production deployment:
        $ fab [noinput] production deploy