]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-38870: Correctly handle empty docstrings in ast.unparse (GH-18768)
authorBatuhan Taskaya <batuhanosmantaskaya@gmail.com>
Sat, 16 May 2020 22:49:07 +0000 (01:49 +0300)
committerGitHub <noreply@github.com>
Sat, 16 May 2020 22:49:07 +0000 (23:49 +0100)
Co-authored-by: Pablo Galindo <Pablogsal@gmail.com>
Lib/ast.py
Lib/test/test_unparse.py

index d6cb334432c9c6e39ebf037b601be19c8887626c..5d0171f10729902e7f6b2ab2d838c63b023bae54 100644 (file)
@@ -1075,11 +1075,14 @@ class _Unparser(NodeVisitor):
         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}"""')
 
index 410df7dbb75818d4cd7e8750f25ccc595d2a6ad5..4f5742852e23ddc748304e4e58b9489a9ec1012f 100644 (file)
@@ -313,11 +313,18 @@ class UnparseTestCase(ASTTestCase):
     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 @@ class CosmeticTestCase(ASTTestCase):
             empty newline"""''',
             '"""With some \t"""',
             '"""Foo "bar" baz """',
+            '"""\\r"""',
+            '""""""',
+            '"""\'\'\'"""',
+            '"""\'\'\'\'\'\'"""',
         )
 
         for prefix in docstring_prefixes: