Skip to content

Commit

Permalink
adjust logical line for FSTRING_MIDDLE brace escaping
Browse files Browse the repository at this point in the history
  • Loading branch information
asottile committed Aug 4, 2024
1 parent 915d771 commit 37c9f60
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 4 additions & 1 deletion pycodestyle.py
Original file line number Diff line number Diff line change
Expand Up @@ -1949,7 +1949,10 @@ def build_tokens_line(self):
if token_type == tokenize.STRING:
text = mute_string(text)
elif token_type == FSTRING_MIDDLE: # pragma: >=3.12 cover
text = 'x' * len(text)
# fstring tokens are "unescaped" braces -- re-escape!
brace_count = text.count('{') + text.count('}')
text = 'x' * (len(text) + brace_count)
end = (end[0], end[1] + brace_count)
if prev_row:
(start_row, start_col) = start
if prev_row != start_row: # different row
Expand Down
19 changes: 19 additions & 0 deletions tests/test_pycodestyle.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import io
import sys
import tokenize

import pytest

from pycodestyle import Checker
from pycodestyle import expand_indent
from pycodestyle import mute_string

Expand Down Expand Up @@ -27,3 +32,17 @@ def test_expand_indent(s, expected):
)
def test_mute_string(s, expected):
assert mute_string(s) == expected


def test_fstring_logical_line():
src = '''\
f'hello {{ {thing} }} world'
'''
checker = Checker(lines=src.splitlines())
checker.tokens = list(tokenize.generate_tokens(io.StringIO(src).readline))
checker.build_tokens_line()

if sys.version_info >= (3, 12): # pragma: >3.12 cover
assert checker.logical_line == "f'xxxxxxxxx{thing}xxxxxxxxx'"
else:
assert checker.logical_line == "f'xxxxxxxxxxxxxxxxxxxxxxxxx'"

0 comments on commit 37c9f60

Please sign in to comment.