Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8d6d760

Browse files
committed
Collapse else: if: ... into elif:
1 parent 719e4e3 commit 8d6d760

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

Demo/parser/test_unparse.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,24 @@ def h():
6464
class Foo: pass
6565
"""
6666

67+
elif1 = """\
68+
if cond1:
69+
suite1
70+
elif cond2:
71+
suite2
72+
else:
73+
suite3
74+
"""
75+
76+
elif2 = """\
77+
if cond1:
78+
suite1
79+
elif cond2:
80+
suite2
81+
"""
82+
83+
84+
6785
class ASTTestCase(unittest.TestCase):
6886
def assertASTEqual(self, ast1, ast2):
6987
self.assertEqual(ast.dump(ast1), ast.dump(ast2))
@@ -159,6 +177,10 @@ def test_class_decorators(self):
159177
def test_class_definition(self):
160178
self.check_roundtrip("class A(metaclass=type, *[], **{}): pass")
161179

180+
def test_elifs(self):
181+
self.check_roundtrip(elif1)
182+
self.check_roundtrip(elif2)
183+
162184
class DirectoryTestCase(ASTTestCase):
163185
"""Test roundtrip behaviour on all files in Lib and Lib/test."""
164186

Demo/parser/unparse.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,9 +256,18 @@ def _If(self, t):
256256
self.fill("if ")
257257
self.dispatch(t.test)
258258
self.enter()
259-
# XXX elif?
260259
self.dispatch(t.body)
261260
self.leave()
261+
# collapse nested ifs into equivalent elifs.
262+
while (t.orelse and len(t.orelse) == 1 and
263+
isinstance(t.orelse[0], ast.If)):
264+
t = t.orelse[0]
265+
self.fill("elif ")
266+
self.dispatch(t.test)
267+
self.enter()
268+
self.dispatch(t.body)
269+
self.leave()
270+
# final else
262271
if t.orelse:
263272
self.fill("else")
264273
self.enter()

0 commit comments

Comments
 (0)