Skip to content

Commit

Permalink
dead versioned if statements can be deleted at module scope
Browse files Browse the repository at this point in the history
  • Loading branch information
asottile committed Jul 3, 2023
1 parent e7fc4db commit ecaa115
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
7 changes: 7 additions & 0 deletions pyupgrade/_plugins/versioned_branches.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
15 changes: 11 additions & 4 deletions tests/features/versioned_branches_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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):
Expand Down

0 comments on commit ecaa115

Please sign in to comment.