Skip to content

Instantly share code, notes, and snippets.

@kini
Created October 7, 2012 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kini/3847209 to your computer and use it in GitHub Desktop.
Save kini/3847209 to your computer and use it in GitHub Desktop.
Comparing ASTs in Python to show that "elif" is desugared in the parser
[1] fs-boone@zhenghe ~/classes/cs321/hw1 $ cat print-ast.py
#!/usr/bin/env python
import sys, ast
print ast.dump(ast.parse(sys.stdin.read()))
[1] fs-boone@zhenghe ~/classes/cs321/hw1 $ cat test1
if x == 1:
print 1
elif x == 2:
print 3
else:
print 'Something else'
[1] fs-boone@zhenghe ~/classes/cs321/hw1 $ cat test2
if x == 1:
print 1
else:
if x == 2:
print 3
else:
print 'Something else'
[1] fs-boone@zhenghe ~/classes/cs321/hw1 $ ./print-ast.py < test1
Module(body=[If(test=Compare(left=Name(id='x', ctx=Load()), ops=[Eq()], comparators=[Num(n=1)]), body=[Print(dest=None, values=[Num(n=1)], nl=True)], orelse=[If(test=Compare(left=Name(id='x', ctx=Load()), ops=[Eq()], comparators=[Num(n=2)]), body=[Print(dest=None, values=[Num(n=3)], nl=True)], orelse=[Print(dest=None, values=[Str(s='Something else')], nl=True)])])])
[1] fs-boone@zhenghe ~/classes/cs321/hw1 $ ./print-ast.py < test2
Module(body=[If(test=Compare(left=Name(id='x', ctx=Load()), ops=[Eq()], comparators=[Num(n=1)]), body=[Print(dest=None, values=[Num(n=1)], nl=True)], orelse=[If(test=Compare(left=Name(id='x', ctx=Load()), ops=[Eq()], comparators=[Num(n=2)]), body=[Print(dest=None, values=[Num(n=3)], nl=True)], orelse=[Print(dest=None, values=[Str(s='Something else')], nl=True)])])])
[1] fs-boone@zhenghe ~/classes/cs321/hw1 $ diff -u <(./print-ast.py < test1) <(./print-ast.py < test2)
[1] fs-boone@zhenghe ~/classes/cs321/hw1 $ echo $?
0
[1] fs-boone@zhenghe ~/classes/cs321/hw1 $ python --version
Python 2.7.3rc2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment