Skip to content

Commit 559b769

Browse files
committed
Manage indentation better in docstrings
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...
1 parent 2f12098 commit 559b769

File tree

2 files changed

+9
-4
lines changed

2 files changed

+9
-4
lines changed

src/labthings/utilities.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import copy
2+
import inspect
23
import operator
34
import os
45
import re
@@ -152,12 +153,12 @@ def get_docstring(obj: Any, remove_newlines=True) -> str:
152153
153154
"""
154155
ds = obj.__doc__
155-
if ds:
156+
if not ds:
157+
return ""
158+
if remove_newlines:
156159
stripped = [line.strip() for line in ds.splitlines() if line]
157-
if not remove_newlines:
158-
return "\n".join(stripped)
159160
return " ".join(stripped).replace("\n", " ").replace("\r", "")
160-
return ""
161+
return inspect.cleandoc(ds) # Strip spurious indentation/newlines
161162

162163

163164
def get_summary(obj: Any) -> str:

tests/test_utilities.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ def test_get_docstring(example_class):
3030
utilities.get_docstring(example_class)
3131
== "First line of class docstring. Second line of class docstring. "
3232
)
33+
assert (
34+
utilities.get_docstring(example_class, remove_newlines=False)
35+
== "First line of class docstring.\nSecond line of class docstring."
36+
)
3337

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

0 commit comments

Comments
 (0)