I have a string expression that I need to do eval on. This expression may have key names from a given dictionary and values for those keys may or may not be strings. For my eval to be able to evaluate those names, I am creating variables with the key names that appear in that dict and assign it the value from the dict as in the example below. But from what I have read here, vars() should nto be used. This has made me worry about the stability as well as risks of what I have implemented. Any thoughts or suggestions to how to implmenet this in a better way?
def test(e1,d1):
for k,v in d1.iteritems():
if k in e1:
vars()[k]=v
return eval(e1)
test('x+y', {'x':1, 'y':2})
Thanks!!
There is a better way to do what you’re trying to do: the optional
globalsandlocalsarguments toeval.does the same thing as your code but without needing to muck with
vars. If you can get away with passing an empty dictionary as the second argument instead ofglobals(), that will insulate you from side effects ofe1.