Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions Lib/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -1001,11 +1001,14 @@ def _write_docstring(self, node):
if node.kind == "u":
self.write("u")

# Preserve quotes in the docstring by escaping them
value = node.value.replace("\\", "\\\\")
value = value.replace('"""', '""\"')
if value[-1] == '"':
value = value.replace('"', '\\"', -1)
value = node.value
if value:
Comment thread
isidentical marked this conversation as resolved.
# Preserve quotes in the docstring by escaping them
value = value.replace("\\", "\\\\")
value = value.replace('"""', '""\"')
Comment thread
isidentical marked this conversation as resolved.
value = value.replace("\r", "\\r")
if value[-1] == '"':
value = value.replace('"', '\\"', -1)
Comment thread
isidentical marked this conversation as resolved.

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

Expand Down
15 changes: 13 additions & 2 deletions Lib/test/test_unparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,11 +304,18 @@ def test_invalid_yield_from(self):
def test_docstrings(self):
docstrings = (
'this ends with double quote"',
'this includes a """triple quote"""'
'this includes a """triple quote"""',
'\r',
'\\r',
'\t',
'\\t',
'\n',
'\\n',
'\r\\r\t\\t\n\\n'
)
for docstring in docstrings:
# check as Module docstrings for easy testing
self.check_ast_roundtrip(f"'{docstring}'")
self.check_ast_roundtrip(f"'''{docstring}'''")


class CosmeticTestCase(ASTTestCase):
Expand Down Expand Up @@ -354,6 +361,10 @@ def test_docstrings(self):
empty newline"""''',
'"""With some \t"""',
'"""Foo "bar" baz """',
'"""\\r"""',
'""""""',
'"""\'\'\'"""',
'"""\'\'\'\'\'\'"""',
)

for prefix in docstring_prefixes:
Expand Down