[Python-checkins] bpo-38870: Correctly handle empty docstrings in ast.unparse (GH-18768)

Batuhan Taskaya webhook-mailer at python.org
Sat May 16 18:49:12 EDT 2020


https://github.com/python/cpython/commit/e966af7cff78e14e1d289db587433504b4b53533
commit: e966af7cff78e14e1d289db587433504b4b53533
branch: master
author: Batuhan Taskaya <batuhanosmantaskaya at gmail.com>
committer: GitHub <noreply at github.com>
date: 2020-05-16T23:49:07+01:00
summary:

bpo-38870: Correctly handle empty docstrings in ast.unparse (GH-18768)

Co-authored-by: Pablo Galindo <Pablogsal at gmail.com>

files:
M Lib/ast.py
M Lib/test/test_unparse.py

diff --git a/Lib/ast.py b/Lib/ast.py
index d6cb334432c9c..5d0171f107299 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -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}"""')
 
diff --git a/Lib/test/test_unparse.py b/Lib/test/test_unparse.py
index 410df7dbb7581..4f5742852e23d 100644
--- a/Lib/test/test_unparse.py
+++ b/Lib/test/test_unparse.py
@@ -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,)")
@@ -390,6 +397,10 @@ def test_docstrings(self):
             empty newline"""''',
             '"""With some \t"""',
             '"""Foo "bar" baz """',
+            '"""\\r"""',
+            '""""""',
+            '"""\'\'\'"""',
+            '"""\'\'\'\'\'\'"""',
         )
 
         for prefix in docstring_prefixes:



More information about the Python-checkins mailing list