Skip to content

Commit 86609e8

Browse files
committed
handle constant folding with comments on multilines better
1 parent 85c6837 commit 86609e8

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

pyupgrade/_token_helpers.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,14 @@ def arg_str(tokens: list[Token], start: int, end: int) -> str:
369369
return tokens_to_src(tokens[start:end]).strip()
370370

371371

372+
def _arg_str_no_comment(tokens: list[Token], start: int, end: int) -> str:
373+
arg_tokens = [
374+
token for token in tokens[start:end]
375+
if token.name != 'COMMENT'
376+
]
377+
return tokens_to_src(arg_tokens).strip()
378+
379+
372380
def _arg_contains_newline(tokens: list[Token], start: int, end: int) -> bool:
373381
while tokens[start].name in {'NL', 'NEWLINE', UNIMPORTANT_WS}:
374382
start += 1
@@ -473,7 +481,7 @@ def replace_argument(
473481
def constant_fold_tuple(i: int, tokens: list[Token]) -> None:
474482
start = find_op(tokens, i, '(')
475483
func_args, end = parse_call_args(tokens, start)
476-
arg_strs = [arg_str(tokens, *arg) for arg in func_args]
484+
arg_strs = [_arg_str_no_comment(tokens, *arg) for arg in func_args]
477485

478486
unique_args = tuple(dict.fromkeys(arg_strs))
479487

tests/features/exceptions_test.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,30 @@ def test_fix_exceptions_version_specific_noop(s, version):
225225
226226
id='leave unrelated error names alone',
227227
),
228+
pytest.param(
229+
'try: ...\n'
230+
'except (\n'
231+
' BaseException,\n'
232+
' BaseException # b\n'
233+
'): ...\n',
234+
235+
'try: ...\n'
236+
'except BaseException: ...\n',
237+
238+
id='dedupe with comment. see #932',
239+
),
240+
pytest.param(
241+
'try: ...\n'
242+
'except (\n'
243+
' A, A,\n'
244+
' B # b\n'
245+
'): ...\n',
246+
247+
'try: ...\n'
248+
'except (A, B): ...\n',
249+
250+
id='dedupe other exception, one contains comment. see #932',
251+
),
228252
),
229253
)
230254
def test_fix_exceptions(s, expected):

0 commit comments

Comments
 (0)