Skip to content

gh-134582: Fix t-strings untokenize() roundtrip removing space between braces #134603

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Lib/test/test_tokenize.py
Original file line number Diff line number Diff line change
Expand Up @@ -1975,6 +1975,10 @@ def test_roundtrip(self):
for case in cases:
self.check_roundtrip(case)

self.check_roundtrip(r"t'{ {}}'")
self.check_roundtrip(r"t'{f'{ {}}'}{ {}}'")
self.check_roundtrip(r"f'{t'{ {}}'}{ {}}'")


def test_continuation(self):
# Balancing continuation
Expand Down
14 changes: 7 additions & 7 deletions Lib/tokenize.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ def compat(self, token, iterable):
toks_append = self.tokens.append
startline = token[0] in (NEWLINE, NL)
prevstring = False
in_fstring = 0
in_fstring_or_tstring = 0

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

if toknum == FSTRING_START:
in_fstring += 1
elif toknum == FSTRING_END:
in_fstring -= 1
if toknum in {FSTRING_START, TSTRING_START}:
in_fstring_or_tstring += 1
elif toknum in {FSTRING_END, TSTRING_END}:
in_fstring_or_tstring -= 1
if toknum == INDENT:
indents.append(tokval)
continue
Expand All @@ -311,8 +311,8 @@ def compat(self, token, iterable):
elif toknum in {FSTRING_MIDDLE, TSTRING_MIDDLE}:
tokval = self.escape_brackets(tokval)

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

# Insert a space between two consecutive f-strings
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix tokenize.untokenize() round-trip errors related to t-strings braces escaping
Loading