Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eval() does not assign variable at runtime

I use eval() to assign a list to a var:

eval('mylist = [1,2,3]') 

but when I run it , I got a SyntaxError. What's wrong with it? If I cannot do assignment in the eval(), how do I assign a var in the runtime.

like image 553
Fei Xue Avatar asked Jun 21 '13 07:06

Fei Xue


1 Answers

Use exec for statements:

>>> exec 'lis = [1,2,3]'
>>> lis
[1, 2, 3]

eval works only on expressions, like 2*2,4+5 etc

eval and exec are okay if the string is coming from a known source, but don't use them if the string is coming from an unknown source(user input).

Read : Be careful with exec and eval in Python

like image 179
Ashwini Chaudhary Avatar answered Sep 21 '22 15:09

Ashwini Chaudhary