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?
-
3What are you trying to do? Whatever you are doing you should not use eval.babsher– babsher2011-04-08 18:29:15 +00:00Commented Apr 8, 2011 at 18:29
-
7Disagree, eval has tons of great usesJoshua– Joshua2020-06-09 23:28:43 +00:00Commented Jun 9, 2020 at 23:28
6 Answers
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.
3 Comments
locals(). (docs.python.org/2/library/functions.html#locals) Is there another way to just use assignment without the full evil of eval()?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.