From 2184b76496f8bb39b1b499c821bd6d9dbc81548e Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Mon, 18 Sep 2023 07:11:56 -0700 Subject: [3.11] gh-108843: fix ast.unparse for f-string with many quotes (#108980) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [3.11] gh-108843: fix ast.unparse for f-string with many quotes * 📜🤖 Added by blurb_it. * simplify --------- Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com> --- Lib/ast.py | 18 +++++++++++++++++- Lib/test/test_unparse.py | 5 +++++ .../2023-09-06-04-30-05.gh-issue-108843.WJMhsS.rst | 1 + 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2023-09-06-04-30-05.gh-issue-108843.WJMhsS.rst diff --git a/Lib/ast.py b/Lib/ast.py index 623b9a1..d84d75e 100644 --- a/Lib/ast.py +++ b/Lib/ast.py @@ -1175,13 +1175,29 @@ class _Unparser(NodeVisitor): new_fstring_parts = [] quote_types = list(_ALL_QUOTES) + fallback_to_repr = False for value, is_constant in fstring_parts: - value, quote_types = self._str_literal_helper( + value, new_quote_types = self._str_literal_helper( value, quote_types=quote_types, escape_special_whitespace=is_constant, ) new_fstring_parts.append(value) + if set(new_quote_types).isdisjoint(quote_types): + fallback_to_repr = True + break + quote_types = new_quote_types + + if fallback_to_repr: + # If we weren't able to find a quote type that works for all parts + # of the JoinedStr, fallback to using repr and triple single quotes. + quote_types = ["'''"] + new_fstring_parts.clear() + for value, is_constant in fstring_parts: + value = repr('"' + value) # force repr to use single quotes + expected_prefix = "'\"" + assert value.startswith(expected_prefix), repr(value) + new_fstring_parts.append(value[len(expected_prefix):-1]) value = "".join(new_fstring_parts) quote_type = quote_types[0] diff --git a/Lib/test/test_unparse.py b/Lib/test/test_unparse.py index f1f1dd5..d8f0060 100644 --- a/Lib/test/test_unparse.py +++ b/Lib/test/test_unparse.py @@ -662,6 +662,11 @@ class CosmeticTestCase(ASTTestCase): self.check_src_roundtrip("[a, b] = [c, d] = [e, f] = g") self.check_src_roundtrip("a, b = [c, d] = e, f = g") + def test_multiquote_joined_string(self): + self.check_ast_roundtrip("f\"'''{1}\\\"\\\"\\\"\" ") + self.check_ast_roundtrip("""f"'''{1}""\\"" """) + self.check_ast_roundtrip("""f'""\"{1}''' """) + self.check_ast_roundtrip("""f'""\"{1}""\\"' """) class DirectoryTestCase(ASTTestCase): diff --git a/Misc/NEWS.d/next/Library/2023-09-06-04-30-05.gh-issue-108843.WJMhsS.rst b/Misc/NEWS.d/next/Library/2023-09-06-04-30-05.gh-issue-108843.WJMhsS.rst new file mode 100644 index 0000000..0f15761 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-09-06-04-30-05.gh-issue-108843.WJMhsS.rst @@ -0,0 +1 @@ +Fix an issue in :func:`ast.unparse` when unparsing f-strings containing many quote types. -- cgit v0.12