Paste #36482
Welcome On LodgeIt
Welcome to the LodgeIt pastebin. In order to use the notification feature a 31 day cookie with an unique ID was created for you. The lodgeit database does not store any information about you, it's just used for an advanced pastebin experience :-). Read more on the about lodgeit page. Have fun :-)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | import ast class GenshiSemantics(ast.NodeTransformer): def context(self, method): return ast.Expr(ast.Call( ast.Attribute(ast.Name('data', ast.Load()), method, ast.Load()), [], [], None, None )) def visit_For(self, node): self.generic_visit(node) return [self.context('push'), node, self.context('pop')] def visit_Name(self, node): self.generic_visit(node) return ast.Subscript( ast.Name('data', ast.Load()), ast.Index(ast.Str(node.id)), node.ctx ) class Context(object): def __init__(self): self.stack = [{}] def __getitem__(self, key): for item in reversed(self.stack): if key in item: return item[key] raise KeyError(key) def __setitem__(self, key, value): self.stack[-1][key] = value def push(self): self.stack.append({}) def pop(self): self.stack.pop() node = ast.parse(''' seq = [1, 2, 3, 4, 5] item = 42 for item in seq: print 'inside', item print 'outside', item ''') node = ast.fix_missing_locations(GenshiSemantics().visit(node)) print 'Code in Python Source:' print ast.to_source(node) print print 'Run it:' code = compile(node, '<template>', 'exec') namespace = {'data': Context()} exec code in namespace |