473,383 Members | 1,788 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Compile AST to bytecode?

Hi,

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?

TIA,
--Rob

Sep 19 '06 #1
3 3231
"Rob De Almeida" <ra******@gmail.comwrote:
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).ge tCode()
>>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 <expressionat 0122D848, file "<string>", line -1>
>>eval(_)
42
Sep 19 '06 #2
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)
--Rob

Sep 19 '06 #3
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
fu******@amor.org

Sep 19 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: John Doe | last post by:
Hello, I'm currently working on a little tool that would benefit from having a little embedded script language. Although I have C++ source code available for such a script language, I have 2...
2
by: Vio | last post by:
I would like to know if executing: c = compile('a=5\nprint a','<string>','exec') on a Linux box, then pickling+beaming the result on a Windows box, will give me the expecting result: >>>...
6
by: Benjamin Scherrey | last post by:
I'm curious as to how difficult it would be to take a string that contains compiled bytecode, load it into memory, give it a function name then execute that function. I'm thinking of a database...
8
by: Nick Coghlan | last post by:
Time for another random syntax idea. . . So, I was tinkering in the interactive interpreter, and came up with the following one-size-fits-most default argument hack: Py> x = 1 Py> def...
33
by: Maurice LING | last post by:
Hi, I've been using Python for about 2 years now, for my honours project and now my postgrad project. I must say that I am loving it more and more now. From my knowledge, Python bytecodes are...
2
by: Charles | last post by:
Dear sirs, I'm doing some investigations on the Python language. I'd like to know if it is possible to compile Python code made for the web (an online database for instance), and to run it using...
0
by: sxanth | last post by:
>What puzzles me, though, are bytecodes 17, 39 and 42 - surely these aren't >reachable? Does the compiler just throw in a default 'return None' >epilogue, with routes there from every code path,...
0
by: Fuzzyman | last post by:
Hello all, The following is a copy of a blog entry. It's asking a question about future statements and the built in compile function. I'd appreciate any pointers or comments about possible...
3
by: schwarz | last post by:
As part of some research I am doing a Python Virtual Machine in Java, and the exact semantics of the STORE_NAME bytecode is unclear to be, so I was hoping somebody here could clarify it. The...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.