Force Sphinx to interpret Markdown in Python docstrings instead of reStructuredText

ぃ、小莉子 提交于 2020-01-01 06:27:09

问题


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:


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()
    for line in rst.splitlines():
        lines.append(line)

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()
    for line in rst.splitlines():
        lines.append(line)

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 the native reStructuredText.



来源:https://stackoverflow.com/questions/56062402/force-sphinx-to-interpret-markdown-in-python-docstrings-instead-of-restructuredt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!