Skip to content

Instantly share code, notes, and snippets.

@zackmdavis
Created March 26, 2015 01:42
Show Gist options
  • Save zackmdavis/cc535f594ff7d4d6c431 to your computer and use it in GitHub Desktop.
Save zackmdavis/cc535f594ff7d4d6c431 to your computer and use it in GitHub Desktop.
# <timburke> acorwin: i don't think i like how your pre-incrementer handles things like `+i; +i`, but i can't think of a good way around it...
# [...]
# <acorwin> timburke: what don't you like about it?
# <acorwin> +i ; +i ; i.val yields 1
# <timburke> acorwin: yes! and they should have both yielded zero!
# <acorwin> timburke: well, they have to return i, but i.__str__() could just be str(i.val)
# <timburke> acorwin: well, yeah. the *state* after each should have been 0
# <acorwin> timburke: oh, well, without delving into the AST i can't actually verify that two +'s are together
# <timburke> acorwin: yeah. like i said, i can't think of a good way around it
# <acorwin> timburke: yeah. oh well.
import ast
from _ast import UAdd, UnaryOp, BinOp, Name, Load, Add, Num, Assign, Store
class PreincrementTransformer(ast.NodeTransformer):
def visit_Expr(self, node):
if (isinstance(node.value, UnaryOp) and isinstance(node.value.op, UAdd) and
isinstance(node.value.operand, UnaryOp) and isinstance(node.value.operand.op, UAdd)):
incrementee_id = node.value.operand.operand.id
return ast.fix_missing_locations(
Assign(
targets=[Name(id=incrementee_id, ctx=Store())],
value=BinOp(left=Name(id=incrementee_id, ctx=Load()), op=Add(),
right=Num(n=1))
)
)
else:
return node
if __name__ == "__main__":
print "Welcome to Python with Preincrementing!"
while True:
try:
user_input = raw_input(">>> ")
user_ast = ast.parse(user_input)
modified_ast = PreincrementTransformer().visit(user_ast)
eval(compile(modified_ast, "<string>", "exec"))
except KeyboardInterrupt:
print "\nFarewell!"
break
# zmd@SuddenHeap:~/Code/Misc$ python preincrement.py
# Welcome to Python with Preincrementing!
# >>> i = 0
# >>> print i
# 0
# >>> ++i
# >>> ++i
# >>> print i
# 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment