To preserve line breaks in Sphinx-generated documentation from Python docstrings, you can format your docstrings using reStructuredText (reST) syntax properly. Sphinx uses reST as the markup language, and for it to respect the line breaks and formatting, you need to adhere to certain conventions.
Here’s how you can modify your docstring:
Arguments
, Returns
, etc.Here’s an updated version of your docstring:
def testMethod(arg1, arg2): """ This is a test method. Arguments: - **arg1**: arg1 description - **arg2**: arg2 description Returns: None """ print("I am a test method")
Key changes:
Arguments
, Returns
, and others. This tells Sphinx to treat them as distinct paragraphs.-
before each argument helps preserve formatting in lists.:
without markup: In reST, :
has a special meaning, so it’s better to use a more structured format.napoleon
extensionSphinx has an extension called sphinx.ext.napoleon
that supports NumPy and Google-style docstrings, making it easier to preserve formatting with simpler syntax.
Enable napoleon
by adding it to your Sphinx configuration (conf.py
):
extensions = [ 'sphinx.ext.napoleon', ]
With napoleon
, you can write your docstring in a clearer format:
def testMethod(arg1, arg2): """ This is a test method. Args: arg1: arg1 description arg2: arg2 description Returns: None """ print("I am a test method")
napoleon
extension to simplify docstring formatting.By following these steps, Sphinx will preserve the line breaks and generate the documentation with the correct structure.