How to assign a value to a variable using eval in python?

Good. So my question is simple: how can I assign a value to a variable using eval in Python? I tried eval('x = 1') , but that will not work. It returns a SyntaxError. Why won't it work?

+50
python
Apr 08 '11 at 18:26
source share
3 answers

Because x=1 is an expression, not an expression. Use exec to run statements.

 >>> exec('x=1') >>> x 1 



By the way, there are many ways to avoid using exec / eval if all you need is a dynamic name for assignment, for example. you can use the setattr function dictionary, or locals() dictionary :

 >>> locals()['y'] = 1 >>> y 1 

Update . Although the above code works in REPL, it will not work inside a function. See Changing Locales in Python for some alternatives if exec out of the question.

+79
Apr 08 2018-11-11T00:
source share

You cannot, because assigning a variable is an operator, not an expression, and eval can only eval expressions. Use exec instead.

Better yet, do not use or tell us what you are actually trying to do so that we can come up with a safe and reasonable solution.

+9
Apr 08 2018-11-11T00:
source share
 x = 0
 def assignNewValueToX (v):
     global x
     x = v

 eval ('assignNewValueToX (1)')
 print (x)

This works ... because python will actually accomplish the assignment of NewValueToX to be able to evaluate the expression. It can be developed further, but I'm sure that there is a better option for almost any needs that you may have.

0
Apr 08 '11 at 18:32
source share



All Articles