Skip to content

Commit

Permalink
Manage indentation better in docstrings
Browse files Browse the repository at this point in the history
get_docstring used to discard all indentation.
It now uses `inspect.cleandoc()` to
remove spurious indents but preserve
intentional ones, which results in more nicely formatted
markdown docstrings.

I have not changed the default remove_newlines=True but I am quite
tempted to do so.

I'm not convinced by the current trailing space if remove_newlines
is True, but have not changed this
behaviour because there's no advantage
to doing so...
  • Loading branch information
rwb27 committed Jul 1, 2021
1 parent 2f12098 commit 559b769
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/labthings/utilities.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import copy
import inspect
import operator
import os
import re
Expand Down Expand Up @@ -152,12 +153,12 @@ def get_docstring(obj: Any, remove_newlines=True) -> str:
"""
ds = obj.__doc__
if ds:
if not ds:
return ""
if remove_newlines:
stripped = [line.strip() for line in ds.splitlines() if line]
if not remove_newlines:
return "\n".join(stripped)
return " ".join(stripped).replace("\n", " ").replace("\r", "")
return ""
return inspect.cleandoc(ds) # Strip spurious indentation/newlines


def get_summary(obj: Any) -> str:
Expand Down
4 changes: 4 additions & 0 deletions tests/test_utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ def test_get_docstring(example_class):
utilities.get_docstring(example_class)
== "First line of class docstring. Second line of class docstring. "
)
assert (
utilities.get_docstring(example_class, remove_newlines=False)
== "First line of class docstring.\nSecond line of class docstring."
)

assert utilities.get_docstring(example_class.class_method) == (
"First line of class method docstring. Second line of class method docstring. "
Expand Down

0 comments on commit 559b769

Please sign in to comment.