Skip to content

Commit 608adf9

Browse files
committed
Issue 25180: Fix Tools/parser/unparse.py for f-strings. Patch by Martin Panter.
1 parent 57b6579 commit 608adf9

File tree

2 files changed

+48
-2
lines changed

2 files changed

+48
-2
lines changed

Lib/test/test_tools/test_unparse.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,15 @@ def check_roundtrip(self, code1, filename="internal"):
134134
class UnparseTestCase(ASTTestCase):
135135
# Tests for specific bugs found in earlier versions of unparse
136136

137+
def test_fstrings(self):
138+
# See issue 25180
139+
self.check_roundtrip(r"""f'{f"{0}"*3}'""")
140+
self.check_roundtrip(r"""f'{f"{y}"*3}'""")
141+
self.check_roundtrip(r"""f'{f"{\'x\'}"*3}'""")
142+
143+
self.check_roundtrip(r'''f"{r'x' f'{\"s\"}'}"''')
144+
self.check_roundtrip(r'''f"{r'x'rf'{\"s\"}'}"''')
145+
137146
def test_del_statement(self):
138147
self.check_roundtrip("del x, y, z")
139148

@@ -264,8 +273,6 @@ def test_files(self):
264273
for d in self.test_directories:
265274
test_dir = os.path.join(basepath, d)
266275
for n in os.listdir(test_dir):
267-
if n == 'test_fstring.py':
268-
continue
269276
if n.endswith('.py') and not n.startswith('bad'):
270277
names.append(os.path.join(test_dir, n))
271278

Tools/parser/unparse.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,45 @@ def _Bytes(self, t):
322322
def _Str(self, tree):
323323
self.write(repr(tree.s))
324324

325+
def _JoinedStr(self, t):
326+
self.write("f")
327+
string = io.StringIO()
328+
self._fstring_JoinedStr(t, string.write)
329+
self.write(repr(string.getvalue()))
330+
331+
def _FormattedValue(self, t):
332+
self.write("f")
333+
string = io.StringIO()
334+
self._fstring_FormattedValue(t, string.write)
335+
self.write(repr(string.getvalue()))
336+
337+
def _fstring_JoinedStr(self, t, write):
338+
for value in t.values:
339+
meth = getattr(self, "_fstring_" + type(value).__name__)
340+
meth(value, write)
341+
342+
def _fstring_Str(self, t, write):
343+
value = t.s.replace("{", "{{").replace("}", "}}")
344+
write(value)
345+
346+
def _fstring_FormattedValue(self, t, write):
347+
write("{")
348+
expr = io.StringIO()
349+
Unparser(t.value, expr)
350+
expr = expr.getvalue().rstrip("\n")
351+
if expr.startswith("{"):
352+
write(" ") # Separate pair of opening brackets as "{ {"
353+
write(expr)
354+
if t.conversion != -1:
355+
conversion = chr(t.conversion)
356+
assert conversion in "sra"
357+
write(f"!{conversion}")
358+
if t.format_spec:
359+
write(":")
360+
meth = getattr(self, "_fstring_" + type(t.format_spec).__name__)
361+
meth(t.format_spec, write)
362+
write("}")
363+
325364
def _Name(self, t):
326365
self.write(t.id)
327366

0 commit comments

Comments
 (0)