How can I assign the value of a variable using eval in python?

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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 https://stackoverflow.com/questions/1450275/modifying-locals-in-python for some alternatives if exec is out of question.

Solution 2 - Python

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.

Solution 3 - Python

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.

Solution 4 - Python

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

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

p.s. this is dangerous

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontewView Question on Stackoverflow
Solution 1 - PythonkennytmView Answer on Stackoverflow
Solution 2 - PythonRafe KettlerView Answer on Stackoverflow
Solution 3 - PythonsanyiView Answer on Stackoverflow
Solution 4 - PythonDomchixView Answer on Stackoverflow