February 20th, 2005, 08:54 PM
using = in eval()
There must be a good reason this doesn't work...
>>> x = 1
>>> eval("x = 2")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 1
x = 2
SyntaxError: invalid syntax
February 21st, 2005, 01:38 AM
The eval() function executes expressions like e.g. "x+1" or "y==47.11".
The eval() function fails for "x = 2" because this is a statement and not an expression.
For dynamic statement execution use the exec statement. E.g.
assigns the value 2 to x, -5 to a and 25 to b.
exec "a = x-7\nb=a**2"
February 21st, 2005, 07:37 AM
Where you can't use eval() to assign the value of an expression to a variable, the value of evaluating the expression can be assigned to the variable like so:
Note: that it isn't safe to use exec and to a lesser extent eval() on user input since both can be used to execute arbitrary commands on the system, which could result to someone taking over the computer or even whipping the hard drive! Keep these in mind and you should be fine .
>>> x = 1
>>> x = eval('2')
>>> x = eval('x + 1')
Hope this helps,