104

Okay. So my question is simple: How can I assign the value of a variable using eval in Python? I tried eval('x = 1') but that won't work. It returns a SyntaxError. Why won't this work?

tew
  • 2,723
  • 5
  • 23
  • 35

5 Answers5

161

Because x=1 is a statement, 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 to assign, e.g. you could use a dictionary, the setattr function, or the locals() dictionary:

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

Update: Although the code above works in the REPL, it won't work inside a function. See Modifying locals in Python for some alternatives if exec is out of question.

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 7
    And btw, if you want to change a variable like this, you probably want a dictionary instead. – Ned Batchelder Apr 08 '11 at 19:31
  • Probably will use a dictionary next time I do something like this. – tew Oct 08 '12 at 17:48
  • 4
    Python docs say you shouldn't modify `locals()`. (http://docs.python.org/2/library/functions.html#locals) Is there another way to just use assignment without the full evil of `eval()`? – Jason S Jun 04 '13 at 20:56
18

You can't, since variable assignment is a statement, not an expression, and eval can only eval expressions. Use exec instead.

Better yet, don't use either and tell us what you're really trying to do so that we can come up with a safe and sane solution.

Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151
2

you can use lambda, like this:

eval('(lambda x=10: x+2)()')
Ganes Dipa
  • 21
  • 1
  • 1
1

You can actually put exec() command inside eval()

So your statement would look like eval("exec('x = 1')")

p.s. this is dangerous

Domchix
  • 11
  • 1
  • 1
0
x = 0
def assignNewValueToX(v):
    global x
    x = v

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

It works... cause python will actually run assignNewValueToX to be able to evaluate the expression. It can be developed further, but I am sure there is a better option for almost any needs one may have.

sanyi
  • 5,999
  • 2
  • 19
  • 30