Force Sphinx to interpret Markdown in Python docst

2020-06-19 06:01发布

I'm using Sphinx to document a python project. I would like to use Markdown in my docstrings to format them. Even if I use the recommonmark extension, it only covers the .md files written manually, not the docstrings.

I use autodoc, napoleon and recommonmark in my extensions.

How can I make sphinx parse markdown in my docstrings?

1条回答
够拽才男人
2楼-- · 2020-06-19 06:45

Sphinx's autodoc extension emits an event named autodoc-process-docstring every time it processes a doc-string. You can hook into that mechanism to convert the syntax from Markdown to reStructuredText.

I do not know why recommonmark does not offer that functionality out of the box. It should be an easy feature to add. Personally, I use m2r for the conversion in my projects. Because it's fast — much faster than pandoc, for example. Speed is important as the conversion happens on the fly and handles each doc-string individually. Other than that, any Markdown-to-reST converter would do.

Install m2r and add the following to Sphinx's configuration file conf.py:

import m2r

def docstring(app, what, name, obj, options, lines):
    md  = '\n'.join(lines)
    rst = m2r.convert(md)
    lines.clear()
    lines += rst.splitlines()

def setup(app):
    app.connect('autodoc-process-docstring', docstring)

[Edited to add…]

Just like above, but with commonmark:

import commonmark

def docstring(app, what, name, obj, options, lines):
    md  = '\n'.join(lines)
    ast = commonmark.Parser().parse(md)
    rst = commonmark.ReStructuredTextRenderer().render(ast)
    lines.clear()
    lines += rst.splitlines()

def setup(app):
    app.connect('autodoc-process-docstring', docstring)

This uses the same Markdown parser as the Sphinx extension recommonmark and is as fast as m2r, which means next to no effect on build time compared to native reStructuredText.

查看更多
登录 后发表回答