Compile AST to bytecode?

R

Rob De Almeida

Hi,

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

Any hints?

TIA,
--Rob
 
D

Duncan Booth

Rob De Almeida said:
I would like to compile an AST to bytecode, so I can eval it later. I
tried using parse.compileast, but it fails:

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.
return compiler.pycodegen.ExpressionCodeGenerator(ast).getCode()
42
 
R

Rob De Almeida

Duncan said:
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:

--Rob
 
F

fumanchu

Rob said:
Thanks, Duncan. It worked perfectly. :)

For arbitrary nodes I just had to wrap them inside an Expression node:

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:
[100, 1, 0, 83]
[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
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top