<\/script>')

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?

+3
source share
2 answers

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
+5
source

For operators, you should use exec:

in Python 2.x:

exec "print 'x + y = ', x + y" in {'x':4,'y':3}

in Python 3.x:

exec("print('x + y = ', x + y)", {'x':4,'y':3})

(, print Python 3, )

0

All Articles