Skip to content

Commit c61fd7c

Browse files
[3.14] gh-134582: Fix t-strings untokenize() roundtrip removing space between braces (GH-134603) (#134659)
gh-134582: Fix t-strings untokenize() roundtrip removing space between braces (GH-134603) (cherry picked from commit 52509cc) Co-authored-by: Loïc Simon <loic.pano@gmail.com>
1 parent cbf4ccf commit c61fd7c

File tree

3 files changed

+12
-7
lines changed

3 files changed

+12
-7
lines changed

Lib/test/test_tokenize.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1975,6 +1975,10 @@ def test_roundtrip(self):
19751975
for case in cases:
19761976
self.check_roundtrip(case)
19771977

1978+
self.check_roundtrip(r"t'{ {}}'")
1979+
self.check_roundtrip(r"t'{f'{ {}}'}{ {}}'")
1980+
self.check_roundtrip(r"f'{t'{ {}}'}{ {}}'")
1981+
19781982

19791983
def test_continuation(self):
19801984
# Balancing continuation

Lib/tokenize.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ def compat(self, token, iterable):
274274
toks_append = self.tokens.append
275275
startline = token[0] in (NEWLINE, NL)
276276
prevstring = False
277-
in_fstring = 0
277+
in_fstring_or_tstring = 0
278278

279279
for tok in _itertools.chain([token], iterable):
280280
toknum, tokval = tok[:2]
@@ -293,10 +293,10 @@ def compat(self, token, iterable):
293293
else:
294294
prevstring = False
295295

296-
if toknum == FSTRING_START:
297-
in_fstring += 1
298-
elif toknum == FSTRING_END:
299-
in_fstring -= 1
296+
if toknum in {FSTRING_START, TSTRING_START}:
297+
in_fstring_or_tstring += 1
298+
elif toknum in {FSTRING_END, TSTRING_END}:
299+
in_fstring_or_tstring -= 1
300300
if toknum == INDENT:
301301
indents.append(tokval)
302302
continue
@@ -311,8 +311,8 @@ def compat(self, token, iterable):
311311
elif toknum in {FSTRING_MIDDLE, TSTRING_MIDDLE}:
312312
tokval = self.escape_brackets(tokval)
313313

314-
# Insert a space between two consecutive brackets if we are in an f-string
315-
if tokval in {"{", "}"} and self.tokens and self.tokens[-1] == tokval and in_fstring:
314+
# Insert a space between two consecutive brackets if we are in an f-string or t-string
315+
if tokval in {"{", "}"} and self.tokens and self.tokens[-1] == tokval and in_fstring_or_tstring:
316316
tokval = ' ' + tokval
317317

318318
# Insert a space between two consecutive f-strings
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix tokenize.untokenize() round-trip errors related to t-strings braces escaping

0 commit comments

Comments
 (0)