Recompile AST?

Chris Spencer usenet.20.evilspam at spamgourmet.com
Thu Nov 10 21:05:16 EST 2005


Leif K-Brooks wrote:
> chrisspen at gmail.com wrote:
> 
>>Is it possible to recompile the AST generated by compiler.parse, back
>>into code or an executable code object?
> 
> 
> Into a bytecode object:
> 
>  >>> from compiler.pycodegen import ModuleCodeGenerator
>  >>> from compiler.misc import set_filename
>  >>> from compiler import parse
>  >>>
>  >>> tree = parse('foo = 42')
>  >>> set_filename('<foo>', tree)
>  >>> code = ModuleCodeGenerator(tree).getCode()
>  >>> exec code
>  >>> foo
>  42
> 
> Into Python source code: <http://ecritters.biz/asttosource.py>.

Thanks, that's exactly what I was looking for. I had almost figured that 
out, but I had overlooked the need for set_filename.

Chris



More information about the Python-list mailing list