]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-127975: Avoid reusing quote types in ast.unparse if not needed (#127980)
authorShantanu <12621235+hauntsaninja@users.noreply.github.com>
Fri, 31 Jan 2025 08:49:06 +0000 (00:49 -0800)
committerGitHub <noreply@github.com>
Fri, 31 Jan 2025 08:49:06 +0000 (08:49 +0000)
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 154d2c8c1f9ebb977934e1c79ceaee6723d912d6..0937c27bdf8a110b624db9be581404ea9a3da3b7 100644 (file)
@@ -1196,9 +1196,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 332919540da4d6217aea7fe5e05a8b576c13a6d4..f6c4f1f3f6476aaed8584d80fb8210c6f8a017dc 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.