Using eval with substitutions

abhishek at ocf.berkeley.edu abhishek at ocf.berkeley.edu
Thu Aug 31 08:28:05 EDT 2006


Fredrik Lundh wrote:
> (I'm afraid I don't really understand the point of your examples; what
> is it you're really trying to do here ?)

A function is passed a bunch of string expressions like,
x = "a+b"
y=  "x*a"
z= "x+y"

where a and b are assumed to have been assigned values in the local
namespace. Now I have to evaluate another string such as,
"z+y+x"

So as you say, I could do:
x=eval(x), y=eval(y), z=eval(z) and finally eval("z+y+x") but the
problem is that the initial strings are in no particular order, so I
don't know the sequence in which to perform the first 3 evaluations. I
was wondering if there was a simple way to 'pattern-match' so that the
required substitutions like z->x+y->x+x*a->(a+b)+(a+b)*a could be done
automatically.

I apologise if this is still not quite clear.

Abhishek




More information about the Python-list mailing list