From ecaa115e5f237cd4da1ae9669f518d75e36db1a9 Mon Sep 17 00:00:00 2001 From: Anthony Sottile Date: Mon, 3 Jul 2023 13:43:13 -0400 Subject: [PATCH] dead versioned if statements can be deleted at module scope --- pyupgrade/_plugins/versioned_branches.py | 7 +++++++ tests/features/versioned_branches_test.py | 15 +++++++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/pyupgrade/_plugins/versioned_branches.py b/pyupgrade/_plugins/versioned_branches.py index e72c3b6c..1215daf2 100644 --- a/pyupgrade/_plugins/versioned_branches.py +++ b/pyupgrade/_plugins/versioned_branches.py @@ -65,6 +65,11 @@ def _fix_py3_block_else(i: int, tokens: list[Token]) -> None: if_block.replace_condition(tokens, [Token('NAME', 'else')]) +def _fix_remove_block(i: int, tokens: list[Token]) -> None: + block = Block.find(tokens, i) + del tokens[block.start:block.end] + + def _eq(test: ast.Compare, n: int) -> bool: return ( isinstance(test.ops[0], ast.Eq) and @@ -152,6 +157,8 @@ def visit_If( ): if node.orelse and not isinstance(node.orelse[0], ast.If): yield ast_to_offset(node), _fix_py2_block + elif node.col_offset == 0 and not node.orelse: + yield ast_to_offset(node), _fix_remove_block elif ( # if six.PY3: is_name_attr( diff --git a/tests/features/versioned_branches_test.py b/tests/features/versioned_branches_test.py index 068d125f..027aa2db 100644 --- a/tests/features/versioned_branches_test.py +++ b/tests/features/versioned_branches_test.py @@ -9,10 +9,7 @@ @pytest.mark.parametrize( 's', ( - # we timidly skip `if` without `else` as it could cause a SyntaxError - 'if six.PY2:\n' - ' pass', - # here's the case where it causes a SyntaxError + # skip `if` without `else` as it could cause a SyntaxError 'if True:\n' ' if six.PY2:\n' ' pass\n', @@ -570,6 +567,16 @@ def test_fix_py3_only_code(s, expected): 'pass', id='sys.version_info >= (3, 6), noelse', ), + pytest.param( + 'print("before")\n' + 'if six.PY2:\n' + ' pass\n' + 'print("after")\n', + + 'print("before")\n' + 'print("after")\n', + id='can remove no-else if at module scope', + ), ), ) def test_fix_py3x_only_code(s, expected):