rr-/docstring_parser

newlines not preserved in google param description

beasteers opened this issue · 0 comments

The Problem

When a parameter contains new lines between the first line and the rest, those new lines are collapsed into a single new line.

def asdf():
    '''asdf 

    Arguments:
        x (int): asdfkjaslfdk

            ajskdfljalsdk
    '''

print(dcp.compose(dcp.parse(asdf.__doc__)))

Renders:

asdf 

Args:
    x (int): asdfkjaslfdk
        ajskdfljalsdk

And this happens even if there's more lines (3, 4, etc.)

But it should restore it faithfully:

asdf 

Args:
    x (int): asdfkjaslfdk

        ajskdfljalsdk

Solution

The problem happens because inspect.cleandoc strips the leading whitespace between the first line and the rest of the description. So the solution is to separate out the leading blank lines and then add them back in after calling cleandoc.

if desc:
    desc = desc[1:] if desc[0] == " " else desc
    if "\n" in desc:
        lines = desc.splitlines(keepends=True)
        first_line, lines = lines[0], lines[1:]
        # pull aside blank lines
        i = next((i for i, l in enumerate(lines) if l.strip()), 0)
        spaces = ''.join(lines[:i])
        rest = ''.join(lines[i:])
        desc = first_line + spaces + inspect.cleandoc(rest)
    desc = desc.strip("\n")

The relevant bit of code is here btw:

before, desc = text.split(":", 1)
if desc:
desc = desc[1:] if desc[0] == " " else desc
if "\n" in desc:
first_line, rest = desc.split("\n", 1)
desc = first_line + "\n" + inspect.cleandoc(rest)
desc = desc.strip("\n")