Using eval with substitutions

Duncan Booth duncan.booth at invalid.invalid
Thu Aug 31 09:13:41 EDT 2006


abhishek at ocf.berkeley.edu wrote:

> 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.
> 
Sounds a bit of an odd thing to do, but:

>>> def evaluate(var, names):
	expr = names[var]
	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]

>>> names = { 'a': 3, 'b': 2, 'x': 'a+b', 'y': 'x*a', 'z': 'x+y' }
>>> evaluate('z', names)
20
>>> names
{'a': 3, 'b': 2, 'y': 15, 'x': 5, 'z': 20}
>>> 




More information about the Python-list mailing list