]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.13] gh-127975: Avoid reusing quote types in ast.unparse if not needed (GH-127980...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Mon, 3 Feb 2025 00:38:44 +0000 (01:38 +0100)
committerGitHub <noreply@github.com>
Mon, 3 Feb 2025 00:38:44 +0000 (00:38 +0000)
gh-127975: Avoid reusing quote types in ast.unparse if not needed (GH-127980)
(cherry picked from commit 8df5193d37f70a1478642c4b456dcc7d6df6c117)

Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
Lib/ast.py
Lib/test/test_unparse.py
Misc/NEWS.d/next/Library/2024-12-20-08-44-12.gh-issue-127975.8HJwu9.rst [new file with mode: 0644]

index d7e51aba5957062a0c2adaf9ee334a8d0bbe80a1..2bf08c86b6e5bf48b0a19ca76bd54b035621bd05 100644 (file)
@@ -1275,9 +1275,14 @@ class _Unparser(NodeVisitor):
                     fallback_to_repr = True
                     break
                 quote_types = new_quote_types
-            elif "\n" in value:
-                quote_types = [q for q in quote_types if q in _MULTI_QUOTES]
-                assert quote_types
+            else:
+                if "\n" in value:
+                    quote_types = [q for q in quote_types if q in _MULTI_QUOTES]
+                    assert quote_types
+
+                new_quote_types = [q for q in quote_types if q not in value]
+                if new_quote_types:
+                    quote_types = new_quote_types
             new_fstring_parts.append(value)
 
         if fallback_to_repr:
index 35394f29fbe49dfb2c33d131a187e5270ee0eb0a..971fdb2ba32170fe1590ac0f8a28f5c0fdadd9f7 100644 (file)
@@ -513,11 +513,13 @@ class CosmeticTestCase(ASTTestCase):
         self.check_src_roundtrip("class X(*args, **kwargs):\n    pass")
 
     def test_fstrings(self):
-        self.check_src_roundtrip("f'-{f'*{f'+{f'.{x}.'}+'}*'}-'")
-        self.check_src_roundtrip("f'\\u2028{'x'}'")
+        self.check_src_roundtrip('''f\'\'\'-{f"""*{f"+{f'.{x}.'}+"}*"""}-\'\'\'''')
+        self.check_src_roundtrip('''f\'-{f\'\'\'*{f"""+{f".{f'{x}'}."}+"""}*\'\'\'}-\'''')
+        self.check_src_roundtrip('''f\'-{f\'*{f\'\'\'+{f""".{f"{f'{x}'}"}."""}+\'\'\'}*\'}-\'''')
+        self.check_src_roundtrip('''f"\\u2028{'x'}"''')
         self.check_src_roundtrip(r"f'{x}\n'")
-        self.check_src_roundtrip("f'{'\\n'}\\n'")
-        self.check_src_roundtrip("f'{f'{x}\\n'}\\n'")
+        self.check_src_roundtrip('''f"{'\\n'}\\n"''')
+        self.check_src_roundtrip('''f"{f'{x}\\n'}\\n"''')
 
     def test_docstrings(self):
         docstrings = (
diff --git a/Misc/NEWS.d/next/Library/2024-12-20-08-44-12.gh-issue-127975.8HJwu9.rst b/Misc/NEWS.d/next/Library/2024-12-20-08-44-12.gh-issue-127975.8HJwu9.rst
new file mode 100644 (file)
index 0000000..597fa41
--- /dev/null
@@ -0,0 +1 @@
+Avoid reusing quote types in :func:`ast.unparse` if not needed.