Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a python line of code using eval() from a map

Tags:

python

eval

Let's say that I have a line of code that is a string:

a="print 'x + y = ', x + y"

Now I want to execute it using eval()

So if I have already given x & y values beforhand, I know that can write:

eval (compile (a,"test.py", "single"))

And it will work great.

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 will go into x & y to come from b.

How do I do this?

like image 791
bachurim09 Avatar asked Jul 12 '26 23:07

bachurim09


1 Answers

Have you checked the documentation for eval()? There's a couple more parameters you can use for exactly this purpose. For example:

>>> b = {'x':4,'y':3}
>>> eval("x + y", b)
7
like image 59
Greg Hewgill Avatar answered Jul 21 '26 11:07

Greg Hewgill