Skip to content
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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

handle constant folding with comments on multilines better #933

Merged
merged 1 commit into from
Feb 18, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 9 additions & 1 deletion pyupgrade/_token_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,14 @@ def arg_str(tokens: list[Token], start: int, end: int) -> str:
return tokens_to_src(tokens[start:end]).strip()


def _arg_str_no_comment(tokens: list[Token], start: int, end: int) -> str:
arg_tokens = [
token for token in tokens[start:end]
if token.name != 'COMMENT'
]
return tokens_to_src(arg_tokens).strip()


def _arg_contains_newline(tokens: list[Token], start: int, end: int) -> bool:
while tokens[start].name in {'NL', 'NEWLINE', UNIMPORTANT_WS}:
start += 1
Expand Down Expand Up @@ -473,7 +481,7 @@ def replace_argument(
def constant_fold_tuple(i: int, tokens: list[Token]) -> None:
start = find_op(tokens, i, '(')
func_args, end = parse_call_args(tokens, start)
arg_strs = [arg_str(tokens, *arg) for arg in func_args]
arg_strs = [_arg_str_no_comment(tokens, *arg) for arg in func_args]

unique_args = tuple(dict.fromkeys(arg_strs))

Expand Down
24 changes: 24 additions & 0 deletions tests/features/exceptions_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,30 @@ def test_fix_exceptions_version_specific_noop(s, version):

id='leave unrelated error names alone',
),
pytest.param(
'try: ...\n'
'except (\n'
' BaseException,\n'
' BaseException # b\n'
'): ...\n',

'try: ...\n'
'except BaseException: ...\n',

id='dedupe with comment. see #932',
),
pytest.param(
'try: ...\n'
'except (\n'
' A, A,\n'
' B # b\n'
'): ...\n',

'try: ...\n'
'except (A, B): ...\n',

id='dedupe other exception, one contains comment. see #932',
),
),
)
def test_fix_exceptions(s, expected):
Expand Down