Skip to content

Commit

Permalink
Merge pull request #933 from asottile/dedupe-exception-classes-comments
Browse files Browse the repository at this point in the history
handle constant folding with comments on multilines better
  • Loading branch information
asottile committed Feb 18, 2024
2 parents 85c6837 + 86609e8 commit 08c9c9f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
10 changes: 9 additions & 1 deletion pyupgrade/_token_helpers.py
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
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

0 comments on commit 08c9c9f

Please sign in to comment.