Skip to content

Commit c464ef7

Browse files
authored
Merge pull request #1252 from PyCQA/fstring-tokens
adjust logical line for FSTRING_MIDDLE brace escaping
2 parents 915d771 + 37c9f60 commit c464ef7

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

pycodestyle.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1949,7 +1949,10 @@ def build_tokens_line(self):
19491949
if token_type == tokenize.STRING:
19501950
text = mute_string(text)
19511951
elif token_type == FSTRING_MIDDLE: # pragma: >=3.12 cover
1952-
text = 'x' * len(text)
1952+
# fstring tokens are "unescaped" braces -- re-escape!
1953+
brace_count = text.count('{') + text.count('}')
1954+
text = 'x' * (len(text) + brace_count)
1955+
end = (end[0], end[1] + brace_count)
19531956
if prev_row:
19541957
(start_row, start_col) = start
19551958
if prev_row != start_row: # different row

tests/test_pycodestyle.py

+19
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
1+
import io
2+
import sys
3+
import tokenize
4+
15
import pytest
26

7+
from pycodestyle import Checker
38
from pycodestyle import expand_indent
49
from pycodestyle import mute_string
510

@@ -27,3 +32,17 @@ def test_expand_indent(s, expected):
2732
)
2833
def test_mute_string(s, expected):
2934
assert mute_string(s) == expected
35+
36+
37+
def test_fstring_logical_line():
38+
src = '''\
39+
f'hello {{ {thing} }} world'
40+
'''
41+
checker = Checker(lines=src.splitlines())
42+
checker.tokens = list(tokenize.generate_tokens(io.StringIO(src).readline))
43+
checker.build_tokens_line()
44+
45+
if sys.version_info >= (3, 12): # pragma: >3.12 cover
46+
assert checker.logical_line == "f'xxxxxxxxx{thing}xxxxxxxxx'"
47+
else:
48+
assert checker.logical_line == "f'xxxxxxxxxxxxxxxxxxxxxxxxx'"

0 commit comments

Comments
 (0)