Skip to content

Commit

Permalink
Merge pull request #994 from asottile/fstring-find-call
Browse files Browse the repository at this point in the history
fix search for .encode(...) call with 3.12+ f-string tokens
  • Loading branch information
asottile authored Dec 17, 2024
2 parents 7dc1fb3 + 832a3a0 commit 2f55fde
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
4 changes: 2 additions & 2 deletions pyupgrade/_plugins/default_encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@
from pyupgrade._data import State
from pyupgrade._data import TokenFunc
from pyupgrade._string_helpers import is_codec
from pyupgrade._token_helpers import find_call
from pyupgrade._token_helpers import find_closing_bracket
from pyupgrade._token_helpers import find_op


def _fix_default_encoding(i: int, tokens: list[Token]) -> None:
i = find_op(tokens, i + 1, '(')
i = find_call(tokens, i + 1)
j = find_closing_bracket(tokens, i)
del tokens[i + 1:j]

Expand Down
14 changes: 14 additions & 0 deletions pyupgrade/_token_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,20 @@ def find_op(tokens: list[Token], i: int, src: str) -> int:
return _find_token(tokens, i, 'OP', src)


def find_call(tokens: list[Token], i: int) -> int:
depth = 0
while depth or not tokens[i].matches(name='OP', src='('):
if is_open(tokens[i]): # pragma: >3.12 cover
depth += 1
elif is_close(tokens[i]):
# why max(...)? --
# ("something").method(...)
# ^--start target--^
depth = max(depth - 1, 0)
i += 1
return i


def find_end(tokens: list[Token], i: int) -> int:
while tokens[i].name != 'NEWLINE':
i += 1
Expand Down
5 changes: 5 additions & 0 deletions tests/features/default_encoding_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@
'f"{x}(".encode()',
id='3.12+ handle open brace in fstring',
),
pytest.param(
'f"{foo(bar)}(".encode("utf-8")',
'f"{foo(bar)}(".encode()',
id='f-string with function call',
),
),
)
def test_fix_encode(s, expected):
Expand Down

0 comments on commit 2f55fde

Please sign in to comment.