3

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?

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanx for the reply.. should there be a difference when the code you execute is "print 'x + y = ', x + y" or "x+y"? since the first dosen't work with what you offerd..
When you're running a statement like print, then you just need to put the pieces together. For example, eval(compile("print x + y", "<string>", "single"), b)
0

For statements, 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})

(of course, print is not a statement in Python 3, so there is no need in this case)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.