Skip to content

Commit

Permalink
Support if with multiple statements inside else
Browse files Browse the repository at this point in the history
Somehow this wasn't quite right yet.
  • Loading branch information
knutwannheden committed Sep 4, 2024
1 parent a01e9b5 commit 6fc39f3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
12 changes: 6 additions & 6 deletions rewrite/rewrite/python/_parser_visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,22 +330,22 @@ def visit_While(self, node):

def visit_If(self, node):
prefix = self.__source_before('if')
single_statement_body = len(node.body) == 1
single_statement_then_body = len(node.body) == 1
condition = j.ControlParentheses(random_id(), self.__whitespace(), Markers.EMPTY,
self.__pad_right(self.__convert(node.test), self.__source_before(
':') if single_statement_body else Space.EMPTY))
':') if single_statement_then_body else Space.EMPTY))
then = self.__pad_right(
self.__convert(node.body[0]) if single_statement_body else self.__convert_block(node.body), Space.EMPTY)
self.__convert(node.body[0]) if single_statement_then_body else self.__convert_block(node.body), Space.EMPTY)
elze = None
if len(node.orelse) > 0:
single_statement_else_body = len(node.orelse) == 1
elze = j.If.Else(
random_id(),
# TODO technically there could be space between else and ':' but likely not common
self.__source_before('el') if isinstance(node.orelse[0], ast.If) else self.__source_before('else:'),
self.__source_before('el') if single_statement_else_body and isinstance(node.orelse[0], ast.If) else self.__source_before('else:') if single_statement_else_body else self.__source_before('else'),
Markers.EMPTY,
self.__pad_right(
# this is always a zero or one element list
self.__convert(node.orelse[0]),
self.__convert(node.orelse[0]) if single_statement_else_body else self.__convert_block(node.orelse),
Space.EMPTY
)
)
Expand Down
18 changes: 17 additions & 1 deletion rewrite/tests/python/all/if_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def test_if():
)


def test_else():
def test_else_single():
# language=python
rewrite_run(
python(
Expand All @@ -30,6 +30,22 @@ def foo(b):
)


def test_else_multiple():
# language=python
rewrite_run(
python(
"""\
def foo(b):
if b:
pass
else:
x = 0
pass
"""
)
)


def test_elfif_else():
# language=python
rewrite_run(
Expand Down

0 comments on commit 6fc39f3

Please sign in to comment.