[Tutor] What Eval() Hath Men Wrought

Michael Janssen Janssen at rz.uni-frankfurt.de
Fri Jun 18 05:30:54 EDT 2004

On Thu, 17 Jun 2004, Tim Johnson wrote:

> <gr>Couldn't resist that subject since I hear
> the eval (the built-in) is 'evil'. </gr>

AFAIK one reason eval is considered harmful, is because it's dangerous
when you eval something that might be dangerous code. So, eval'ing input
you get from a website is an enormous bad idea.

Imaging you've got the os modul imported, an attacker can do anything with
os.system . "eval" will only eval expresions no statements, wich means
that the attacker can't do an "import os" but there is a workaround:


Given you run this on Linux, the commandline tool "ls" will list the
current directory, but it could have been as easily a more destructive

So, one reason eval is evil is that it will eval anything including evil
code. OTOH, there is nothing wrong about eval'ing your own input (so long
as you know that your input will get eval'ed).

Another reason might be, that it lends to untestable and un-re-usable
code. Look at what eval does: it turns a string into functionality. The
"normal" way to get functionality is using functions. Functions have
defined input-output behaviour: they take arguments and return
return-values. Eval don't do this but uses the variables it finds in
current namespace and can create new variables. Such side-effects have to
be taken into account when you want to write test code or re-use code
containing eval. This means you will have to set up the proper variables
expected by your to-be-evaled-string and you will have to go on with the
variables created within the eval'ed- string.

Anyway, eval can be used - but keep care. Don't eval untrusted input and
keep the to-be-evaled-code short: Fixing errors within strings is harder
than in normal python code, because the traceback output tends to be less


> I've been looking through the Python Cookbook, and
> there's an example at
>   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018
> look for
>   class Eval:
>      # ...... code following
> This appears to be a handy class, but given the concerns about
> built-in function eval, I would welcome comments and caveats.

More information about the Tutor mailing list