Re: Using eval with substitutions
- From: Duncan Booth <duncan.booth@xxxxxxxxxxxxxxx>
- Date: 31 Aug 2006 13:13:41 GMT
abhishek@xxxxxxxxxxxxxxxx wrote:
So as you say, I could do:Sounds a bit of an odd thing to do, but:
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.
expr = names[var]def evaluate(var, names):
names['__builtins__'] = {}
if isinstance(expr, basestring):
del names[var]
code = compile(expr, "<%s>"%var, "eval")
for v in code.co_names:
evaluate(v, names)
names[var] = eval(code, names, names)
del names['__builtins__']
return names[var]
20names = { 'a': 3, 'b': 2, 'x': 'a+b', 'y': 'x*a', 'z': 'x+y' }
evaluate('z', names)
{'a': 3, 'b': 2, 'y': 15, 'x': 5, 'z': 20}names
.
- References:
- Using eval with substitutions
- From: abhishek
- Re: Using eval with substitutions
- From: Fredrik Lundh
- Re: Using eval with substitutions
- From: abhishek
- Using eval with substitutions
- Prev by Date: Re: a question about my script
- Next by Date: simultaneous copy to multiple media
- Previous by thread: Re: Using eval with substitutions
- Next by thread: Tkinter listbox question
- Index(es):
Relevant Pages
|