Executing a python line of code using eval () from a map
Let's say that I have a line of code that is a line:
a="print 'x + y = ', x + y"
Now I want to execute it using eval ()
So, if I already set the values of x and y, I know that I can write:
eval (compile (a,"test.py", "single"))
And that will work just fine.
But I want to give them values from a dict. In other words, if I have a dict:
b={'x':4,'y':3}
I want the values that go into x and y to be obtained from b.
How to do it?
Have you checked the documentation foreval() ? There are a few more options that you can use for this very purpose. For instance:
>>> b = {'x':4,'y':3}
>>> eval("x + y", b)
7