7

I'm currently migrating all existing (incomplete) documentation to Sphinx.

The problem is that the documentation uses Python docstrings (the module is written in C, but it probably does not matter) and the class documentation must be converted into a form usable for Sphinx.

There is sphinx.ext.autodoc, but it automatically puts current docstrings to the document. I want to generate a source file in (RST) based on current docstrings, which I could then edit and improve manually.

How would you transform docstrings into RST for Sphinx?

mzjn
  • 48,958
  • 13
  • 128
  • 248
Michal Čihař
  • 9,799
  • 6
  • 49
  • 87

3 Answers3

13

The autodoc does generate RST only there is no official way to get it out of it. The easiest hack to get it was by changing sphinx.ext.autodoc.Documenter.add_line method to emit me the line it gets.

As all I want is one time migration, output to stdout is good enough for me:

def add_line(self, line, source, *lineno):
    """Append one line of generated reST to the output."""
    print(self.indent + line)
    self.directive.result.append(self.indent + line, source, *lineno)

Now autodoc prints generated RST on stdout while running and you can simply redirect or copy it elsewhere.

Michal Čihař
  • 9,799
  • 6
  • 49
  • 87
  • Nice, I just want to add the directory of that file `~/.virtualenvs/docs/lib/python2.7/site-packages/sphinx/ext/`, if you use virtualenv. File name is, of course, `autodoc.py` – Alan Dong Jul 14 '14 at 17:54
  • For newbies like me, remember to use parens in Python 3.x, the new line should be `print(self.indent + line)` – chrisinmtown Apr 08 '20 at 15:16
4

monkey patching autodoc so it works without needing to edit anything:

import sphinx.ext.autodoc
rst = []
def add_line(self, line, source, *lineno):
    """Append one line of generated reST to the output."""
    rst.append(line)
    self.directive.result.append(self.indent + line, source, *lineno)
sphinx.ext.autodoc.Documenter.add_line = add_line
try:
    sphinx.main(['sphinx-build', '-b', 'html', '-d', '_build/doctrees', '.', '_build/html'])
except SystemExit:
    with file('doc.rst', 'w') as f:
        for line in rst:
            print >>f, line
srepmub
  • 104
  • 3
0

As far as I know there are no automated tools to do this. My approach would therefore be to write a small script that reads relevant modules (based on sphinc.ext.autodoc) and throws doc strings into a file (formatted appropriately).

Alex Gaynor
  • 14,353
  • 9
  • 63
  • 113