[Tutor] Converting string or list to sum [just be careful about eval()]

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Jan 29 16:28:45 EST 2004



On Thu, 29 Jan 2004, Iain wrote:

>  I think I can put two ideas together to solve it for lists :
>  >>> a=[2, 3, '+', 4]
>  >>> d=""
>  >>> for item in range(len(a)):
>
>  ...     d=d+str(a[item])
>  ...
>
>  >>> d
>  '23+4'
>
>  >>> eval(d)
>  27
>
>  I didn't realise eval did that - very handy.


Hello!


eval() is very handy, but just be very careful with who you let type into
it.  Since you're using it for learning Tkinter, it's fine to use it, but
if you were to do that in production code, you have to take more
responsible precautions.  Simply put: eval() can be dangerous in the wrong
hands.



eval() exposes Python itself to the outside world, so not only will the
person doing input be able to do arithmetic, but they can do even more
interesting things, like

###
>>> eval("__import__('math').sqrt(42)")
6.4807406984078604
###



By default, every library module is exposed to the outside world, and
anyone can use the __import__() built-in to get at things.  And it's even
possible to get the system to go into RuntimeErrors with some lambda
trickery:

###
>>> eval("(lambda f: f(f))(lambda g: g(g))")
  File "<string>", line 1, in <lambda>
  File "<string>", line 1, in <lambda>
  File "<string>", line 1, in <lambda>
  File "<string>", line 1, in <lambda>
[... lot of errors later]
RuntimeError: maximum recursion depth exceeded
###


(Don't worry too much about what in the world that lambda expression is
doing: it's just a disguised version of:

###
def f(): f()
###

in lambda expression form.)


And these are just harmless expressions, compared to the really evil ones
that one could construct, given enough malicious imagination.


So be careful about eval(): It's not just giving access to simple
arithmetic, but to the whole Python system.



Hope this helps!




More information about the Tutor mailing list