Docstring to Markdown Converter
The `docstring-to-markdown` library provides on-the-fly conversion of Python docstrings into Markdown format. It currently supports reStructuredText and has initial support for Google-formatted docstrings since version 0.13. The current version is 0.17, and it is actively maintained with a regular release cadence as evidenced by its release history on PyPI.
Warnings
- gotcha The `convert` function raises `UnknownFormatError` if it cannot recognize the format of the input docstring. Ensure your docstrings adhere to either reStructuredText or Google-style conventions for successful conversion.
- gotcha The library primarily operates on docstring strings. It does not parse full Python source files to extract docstrings; you must provide the docstring content as a string to the `convert` function.
- gotcha While supporting reStructuredText and Google-style, the conversion might not cover all intricate features or edge cases of these formats perfectly, especially for highly complex or custom directives. The conversion aims for 'on the fly' utility, not necessarily full fidelity for all Sphinx-like capabilities.
Install
-
pip install docstring-to-markdown
Imports
- convert
import docstring_to_markdown markdown_output = docstring_to_markdown.convert(docstring_content)
- UnknownFormatError
from docstring_to_markdown import UnknownFormatError
Quickstart
import docstring_to_markdown
def my_function_rst(param1, param2):
"""
My function in reStructuredText format.
:param param1: The first parameter.
:type param1: str
:param param2: The second parameter.
:type param2: int
:returns: A concatenated string.
:rtype: str
.. code-block:: python
print('Example usage')
"""
return f"{param1}-{param2}"
def my_function_google(param1, param2):
"""
My function in Google style format.
Args:
param1 (str): The first parameter.
param2 (int): The second parameter.
Returns:
str: A concatenated string.
Example:
>>> my_function_google('hello', 123)
'hello-123'
"""
return f"{param1}-{param2}"
# Convert a reStructuredText docstring
python_code = my_function_rst.__doc__
markdown_output = docstring_to_markdown.convert(python_code)
print(f"ReStructuredText to Markdown:\n{markdown_output}\n")
# Convert a Google-style docstring
python_code_google = my_function_google.__doc__
markdown_output_google = docstring_to_markdown.convert(python_code_google)
print(f"Google style to Markdown:\n{markdown_output_google}")
# Example of an unrecognised format raising an error
try:
docstring_to_markdown.convert('This is a plain docstring without a recognized format.')
except docstring_to_markdown.UnknownFormatError:
print("Successfully caught UnknownFormatError for unrecognized format.")