Parsing variables out of python lines

Mark Hobbes2176 at yahoo.com
Mon Oct 7 01:14:59 EDT 2002


Well, the subject says it all but here is the idea of what I want to do:

foo = [1,2,3]

x = "for i in foo :"

for p in string.split(x):
    if p in vars():
        print eval(p),
    else:
        print p,
print

Then the output is:

"for i in [1,2,3] :"

Now, you'll notice the odd little space between foo and ":" (in the 
assignment to x).  That's b/c my only parsing work is to split on " " 
(spaces).  I don't really want to make the user type in ugly python 
(imagine:  bar( var ) being required!).

I can get rid of this restriction by doing a lot of work (*wink*):

seq = parser.suite(x)
print parser.ast2tuple(seq)

However, this requires modifying x to  x = "for i in foo:pass" so that x 
will compile (be a legal python item).  It also requires parsing the parse 
tree (how ironic) to get out the information about which tokens are 
variables.  This isn't hard but it seems like overkill.  

Is there a middle ground?  I thought about digging through the python 
grammar and finding all the cases where a variable token could occur and 
specifying them in REs but, hey, don't we all hate REs?

I guess lisp still has us in one area (simplicity of self-parsing).

Regards,
Mark



More information about the Python-list mailing list