docstring_parser
docstring_parser copied to clipboard
newlines not preserved in google param description
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: https://github.com/rr-/docstring_parser/blob/53a24833f7cb73c0820c098c7ffc04df3f2c16e0/docstring_parser/google.py#L113-L119