Skip to content

Commit 706789e

Browse files
authored
Merge pull request #856 from asottile/versioned-branches-module-level
dead versioned if statements can be deleted at module scope
2 parents e7fc4db + ecaa115 commit 706789e

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

pyupgrade/_plugins/versioned_branches.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,11 @@ def _fix_py3_block_else(i: int, tokens: list[Token]) -> None:
6565
if_block.replace_condition(tokens, [Token('NAME', 'else')])
6666

6767

68+
def _fix_remove_block(i: int, tokens: list[Token]) -> None:
69+
block = Block.find(tokens, i)
70+
del tokens[block.start:block.end]
71+
72+
6873
def _eq(test: ast.Compare, n: int) -> bool:
6974
return (
7075
isinstance(test.ops[0], ast.Eq) and
@@ -152,6 +157,8 @@ def visit_If(
152157
):
153158
if node.orelse and not isinstance(node.orelse[0], ast.If):
154159
yield ast_to_offset(node), _fix_py2_block
160+
elif node.col_offset == 0 and not node.orelse:
161+
yield ast_to_offset(node), _fix_remove_block
155162
elif (
156163
# if six.PY3:
157164
is_name_attr(

tests/features/versioned_branches_test.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,7 @@
99
@pytest.mark.parametrize(
1010
's',
1111
(
12-
# we timidly skip `if` without `else` as it could cause a SyntaxError
13-
'if six.PY2:\n'
14-
' pass',
15-
# here's the case where it causes a SyntaxError
12+
# skip `if` without `else` as it could cause a SyntaxError
1613
'if True:\n'
1714
' if six.PY2:\n'
1815
' pass\n',
@@ -570,6 +567,16 @@ def test_fix_py3_only_code(s, expected):
570567
'pass',
571568
id='sys.version_info >= (3, 6), noelse',
572569
),
570+
pytest.param(
571+
'print("before")\n'
572+
'if six.PY2:\n'
573+
' pass\n'
574+
'print("after")\n',
575+
576+
'print("before")\n'
577+
'print("after")\n',
578+
id='can remove no-else if at module scope',
579+
),
573580
),
574581
)
575582
def test_fix_py3x_only_code(s, expected):

0 commit comments

Comments
 (0)