473,406 Members | 2,633 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,406 software developers and data experts.

Changing an AST

Is it possible compiler.parse a statement, then change and then
execute/resolve it?

Background:
I'm probably to lazy to write my own parser.

I have such a statement as string: "distance = x**2 + y**2"
x and y are undefined, so it is no executable Python code, but it is
parseable. Now i'd like traverse through the AST and change Name('x')
for the value i have elsewhere. And finally let Python resolve the
computation.

More Background:
I want to write a simulation game with many interdepended values. I
don't want to create a class with dozens of functions, but let Python
create/evaluate them.

I hope this can be understood ;)

Oct 10 '05 #1
4 1577
"beza1e1" <an*************@googlemail.com> wrote:
I have such a statement as string: "distance = x**2 + y**2"
x and y are undefined, so it is no executable Python code, but it is
parseable. Now i'd like traverse through the AST and change Name('x')
for the value i have elsewhere. And finally let Python resolve the
computation.


you can use the parser class for this purpose:

http://www.effbot.org/librarybook/parser.htm

instead of manipulating the parse tree, you can use the AST to identify
the variables, create a dictionary with the current values, and use exec
or eval to evaluate it.

or you can use a regular expression to dig out all variable names.

or you can compile the expression and analyze the code object to find
the variable names, and use the dictionary/exec approach:
expr = compile("distance = x**2 + y**2", "", "exec")
expr.co_varnames ('distance',) list(set(expr.co_names) - set(expr.co_varnames)) ['y', 'x'] context = {"x": 10, "y": 20}
exec expr in context
context["distance"]

500

(the regular expression approach is probably the only one that's
guaranteed to work on all python implementations)

</F>

Oct 10 '05 #2
beza1e1 wrote:
Is it possible compiler.parse a statement, then change and then
execute/resolve it?


This should work:

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

Also, if you need to turn an AST back into Python code, I have some ugly
code for doing that: <http://ecritters.biz/asttosource.py>.
Oct 10 '05 #3
Thank you! this "compile/exec in context" is the thing i wanted.

It is not that performant i think. But it should ease the prototyping.

Oct 10 '05 #4
"beza1e1" wrote:
Thank you! this "compile/exec in context" is the thing i wanted.

It is not that performant i think.


it's about as fast as it can get, as long as you only call compile when
the expressions change. (the example didn't show it, but the "expr"
code object can of course be reused with different contexts)

</F>

Oct 10 '05 #5

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

Similar topics

3
by: Geoff Soper | last post by:
I'm trying to dynamically change the cursor of a couple of maps over an image. Basically the image is in an online photo system where there is a rotate mode. In this mode clicking on the left or...
2
by: Urs Vogel | last post by:
Hi When using XmlDocument, I can create nodes and attributes as I like. What I didn't achieve is changing the Value of a node (created with createElement), it claims that it's the wrong node...
1
by: Paul Reddin | last post by:
Hi, Can anyone tell me if the changing of DB Objects in Stinger has been improved ? e.g Changing optionality, renaming etc..... I spend an awful lot of time changing objects because many...
6
by: Eric | last post by:
I have an array, result. I populate the array and add it to an ArrayList. I then change result and add the new version to the ArrayList. However, when I go to review the ArrayList, all of the...
10
by: Altman | last post by:
I have only done a little programming in C++ so I am still learning but I am having a problem with a variable that is changing on me. I have tried this 2 ways with the same result. I have a...
3
by: John | last post by:
I have an asp.net control which on the first Load of the page has a unique ID something like: _ctl0__ctl1_GroupName__ctl1_ControlName and after the first postback it changes to: ...
1
by: Pablo | last post by:
I do not know like changing the color of bottom of: a menu, of the bar of the title of form, messagebox?
32
by: deko | last post by:
I have a popup form with a textbox that is bound to a memo field. I've been warned about memo fields so I'm wondering if I should use this code. Is there any risk with changing the form's...
18
by: Chris Hills | last post by:
A lesson in Posting How many C.L.C group posters does it take to change a C light bulb? 1 to change the light bulb and to post that the light bulb has been changed 14 to share similar...
1
by: DrJarmin | last post by:
Hello The problem is this: in the criteria for a list box I reference the parent form - and Access KEEPS changing the criteria for one that won't work. Details below: I have a couple of list...
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: 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...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.