Skip to content

Commit

Permalink
bpo-38870: Correctly handle empty docstrings in ast.unparse (GH-18768)
Browse files Browse the repository at this point in the history
Co-authored-by: Pablo Galindo <Pablogsal@gmail.com>
  • Loading branch information
isidentical and pablogsal committed May 16, 2020
1 parent d5a980a commit e966af7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
13 changes: 8 additions & 5 deletions Lib/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -1075,11 +1075,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:
# Preserve quotes in the docstring by escaping them
value = value.replace("\\", "\\\\")
value = value.replace('"""', '""\"')
value = value.replace("\r", "\\r")
if value[-1] == '"':
value = value.replace('"', '\\"', -1)

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 @@ -313,11 +313,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}'''")

def test_constant_tuples(self):
self.check_src_roundtrip(ast.Constant(value=(1,), kind=None), "(1,)")
Expand Down Expand Up @@ -390,6 +397,10 @@ def test_docstrings(self):
empty newline"""''',
'"""With some \t"""',
'"""Foo "bar" baz """',
'"""\\r"""',
'""""""',
'"""\'\'\'"""',
'"""\'\'\'\'\'\'"""',
)

for prefix in docstring_prefixes:
Expand Down

0 comments on commit e966af7

Please sign in to comment.