Rob De Almeida wrote: > Duncan Booth wrote: > > > I would like to compile an AST to bytecode, so I can eval it later. > > I'm not sure there are any properly documented functions for converting an > > AST to a code object, so your best bet may be to examine what a > > pycodegen class like Expression or Module actually does. > > Thanks, Duncan. It worked perfectly. :-) > > For arbitrary nodes I just had to wrap them inside an Expression node: > > >>> ast = compiler.ast.Expression(node) > >>> ast.filename = 'dummy' > >>> c = compiler.pycodegen.ExpressionCodeGenerator(ast) > >>> obj = eval(c.getCode(), scope)
If you're only worried about expressions, then you can have CPython do the compilation for you much faster by wrapping the expression in a lambda: >>> f = lambda: 42 >>> f.func_code.co_code 'd\x01\x00S' >>> map(ord, _) [100, 1, 0, 83] >>> g = lambda x, y: (x * 3) + len(y) >>> map(ord, g.func_code.co_code) [124, 0, 0, 100, 1, 0, 20, 116, 1, 0, 124, 1, 0, 131, 1, 0, 23, 83] For a complete round-trip Expression library, see http://projects.amor.org/dejavu/browser/trunk/logic.py Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list