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:

  1. Use proper reST block formatting: Sphinx needs explicit newlines or paragraphs to render line breaks properly.
  2. Add empty lines before sections like 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:

  • Blank lines: Ensure there are blank lines between sections like Arguments, Returns, and others. This tells Sphinx to treat them as distinct paragraphs.
  • Bullet points: The use of bullet points or - before each argument helps preserve formatting in lists.
  • Avoid using : without markup: In reST, : has a special meaning, so it’s better to use a more structured format.

Another Option: Use the napoleon extension

Sphinx 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")

Summary of Solutions:

  • Ensure proper blank lines between sections in reST format.
  • Use bullet points or item lists for parameters.
  • Optionally, use the napoleon extension to simplify docstring formatting.

By following these steps, Sphinx will preserve the line breaks and generate the documentation with the correct structure.