Compile AST to bytecode?

fumanchu fumanchu at amor.org
Tue Sep 19 11:29:50 EDT 2006


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
fumanchu at amor.org




More information about the Python-list mailing list