Compile AST to bytecode?

Duncan Booth duncan.booth at invalid.invalid
Tue Sep 19 08:56:46 EDT 2006


"Rob De Almeida" <ralmeida at gmail.com> wrote:

> I would like to compile an AST to bytecode, so I can eval it later. I
> tried using parse.compileast, but it fails:
> 
>>>> import compiler, parser
>>>> ast = compiler.parse("42")
>>>> parser.compileast(ast)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: compilest() argument 1 must be parser.st, not instance
> 
> Any hints?

There are two distinct varieties of AST in the Python standard library. 
compiler and parser ast objects are not compatible.

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.

>>> import compiler
>>> def ast_to_evalcode(ast):
	return compiler.pycodegen.ExpressionCodeGenerator(ast).getCode()

>>> def parse_to_ast(src):
	return compiler.pycodegen.Expression(src, "<string>")._get_tree()

>>> ast = parse_to_ast("40+2")
>>> ast
Expression(Add((Const(40), Const(2))))
>>> ast_to_evalcode(ast)
<code object <expression> at 0122D848, file "<string>", line -1>
>>> eval(_)
42



More information about the Python-list mailing list