Skip to content

Commit e966af7

Browse files
bpo-38870: Correctly handle empty docstrings in ast.unparse (GH-18768)
Co-authored-by: Pablo Galindo <[email protected]>
1 parent d5a980a commit e966af7

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

Lib/ast.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1075,11 +1075,14 @@ def _write_docstring(self, node):
10751075
if node.kind == "u":
10761076
self.write("u")
10771077

1078-
# Preserve quotes in the docstring by escaping them
1079-
value = node.value.replace("\\", "\\\\")
1080-
value = value.replace('"""', '""\"')
1081-
if value[-1] == '"':
1082-
value = value.replace('"', '\\"', -1)
1078+
value = node.value
1079+
if value:
1080+
# Preserve quotes in the docstring by escaping them
1081+
value = value.replace("\\", "\\\\")
1082+
value = value.replace('"""', '""\"')
1083+
value = value.replace("\r", "\\r")
1084+
if value[-1] == '"':
1085+
value = value.replace('"', '\\"', -1)
10831086

10841087
self.write(f'"""{value}"""')
10851088

Lib/test/test_unparse.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -313,11 +313,18 @@ def test_invalid_yield_from(self):
313313
def test_docstrings(self):
314314
docstrings = (
315315
'this ends with double quote"',
316-
'this includes a """triple quote"""'
316+
'this includes a """triple quote"""',
317+
'\r',
318+
'\\r',
319+
'\t',
320+
'\\t',
321+
'\n',
322+
'\\n',
323+
'\r\\r\t\\t\n\\n'
317324
)
318325
for docstring in docstrings:
319326
# check as Module docstrings for easy testing
320-
self.check_ast_roundtrip(f"'{docstring}'")
327+
self.check_ast_roundtrip(f"'''{docstring}'''")
321328

322329
def test_constant_tuples(self):
323330
self.check_src_roundtrip(ast.Constant(value=(1,), kind=None), "(1,)")
@@ -390,6 +397,10 @@ def test_docstrings(self):
390397
empty newline"""''',
391398
'"""With some \t"""',
392399
'"""Foo "bar" baz """',
400+
'"""\\r"""',
401+
'""""""',
402+
'"""\'\'\'"""',
403+
'"""\'\'\'\'\'\'"""',
393404
)
394405

395406
for prefix in docstring_prefixes:

0 commit comments

Comments
 (0)