Python docstring whitespace strip for single lines

Python does not consistently handle whitespace stripping of
contents in __doc__ across different versions and interfaces.
For example python-3.13 heap types don't strip whitespace
but but static types do. Python-3.12 and earlier didn't strip
any whitespace either. inspect.getdoc() does consistently remove
docstrings though. Given the whitespace is pointless, SWIG now
strips this off for single line docstrings.
This commit is contained in:
William S Fulton 2024-09-28 15:30:30 +01:00
parent ad036e98d7
commit 9018a9a90b
3 changed files with 30 additions and 10 deletions

View File

@ -87,16 +87,21 @@ check(inspect.getdoc(DocStrings.docstringC),
"second line" "second line"
) )
# One line doc special case, use __doc__ # One line doc special case, use __doc__ to check for stripped whitespace
if sys.version_info[0:2] < (3, 13): check(DocStrings.docstringW.__doc__, "one line docs")
check(DocStrings.docstringX.__doc__, " one line docs") check(DocStrings.docstringX.__doc__, "one line docs leading whitespace")
else: check(DocStrings.docstringY.__doc__, "one line docs trailing whitespace")
check(DocStrings.docstringX.__doc__, "one line docs") check(DocStrings.docstringZ.__doc__, "one line docs whitespace")
check(inspect.getdoc(DocStrings.docstringW),
"one line docs"
)
check(inspect.getdoc(DocStrings.docstringX), check(inspect.getdoc(DocStrings.docstringX),
"one line docs" "one line docs leading whitespace"
) )
check(inspect.getdoc(DocStrings.docstringY), check(inspect.getdoc(DocStrings.docstringY),
"one line docs" "one line docs trailing whitespace"
)
check(inspect.getdoc(DocStrings.docstringZ),
"one line docs whitespace"
) )

View File

@ -77,8 +77,10 @@ line 3
%{ first line %{ first line
second line%} second line%}
%feature("docstring") docstringX " one line docs" %feature("docstring") docstringW "one line docs"
%feature("docstring") docstringY "one line docs" %feature("docstring") docstringX " one line docs leading whitespace"
%feature("docstring") docstringY "one line docs trailing whitespace\t "
%feature("docstring") docstringZ "\tone line docs whitespace \t"
%inline %{ %inline %{
struct DocStrings { struct DocStrings {
@ -92,7 +94,9 @@ struct DocStrings {
void docstringA() {} void docstringA() {}
void docstringB() {} void docstringB() {}
void docstringC() {} void docstringC() {}
void docstringW() {}
void docstringX() {} void docstringX() {}
void docstringY() {} void docstringY() {}
void docstringZ() {}
}; };
%} %}

View File

@ -1614,6 +1614,17 @@ public:
Append(tmp, indent); Append(tmp, indent);
Delete(docstr); Delete(docstr);
docstr = tmp; docstr = tmp;
} else {
// Removing leading and trailing whitespace for single line docstrings
Chop(docstr);
const char *c = Char(docstr);
if (isspace((int)*c)) {
while(isspace((int)*(++c))) {
}
String *old_docstr = docstr;
docstr = NewString(c);
Delete(old_docstr);
}
} }
return docstr; return docstr;