[Tutor] What Eval() Hath Men Wrought

Magnus Lyckå magnus at thinkware.se
Fri Jun 18 06:54:38 EDT 2004


At 18:34 2004-06-17 -0800, Tim Johnson wrote:
><gr>Couldn't resist that subject since I hear
>the eval (the built-in) is 'evil'. </gr>
>
>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.

As I see it, there are some problems with eval()
  - It's slow, e.g. eval('5') is about ten times slower than int('5').
  - It might cause unpredicted results unless you are certain about
    what you run eval on. This isn't really a problem if you only run
    eval on hardcoded strings in your source code as the Cookbook
    example does. In some programs eval could cause security problems.
    For instance, an attacker might be able to display passwords stored
    in program variables etc.
  - It makes it more difficult to analyse the code, for instance with
    some automatic tool such as PyChecker or PyLint. (Or manually for
    that matter.)
  - Debugging get's harder. You might hide syntax errors until runtime
    etc. I imagine tracebacks are less helpful too.

Besides, I'm not really sure that
     print "%(text.capitalize())s %(number/9.0).1f rules!" % Eval()
is better than
     print "% %.1f rules!" % (text.capitalize(), number/9.0)

This is some kind of ASP syndrome, and it seems to me that most
programmers seem to agree that mixing code in text as in ASP or
as in the Eval example typically causes maintenance problems.
Whether we're talking about web pages or something else, we'll
often want to separate the maintenace of the text from the
maintenance of the code. I often do things similar to:

   params = dict(capText=text.capitalize(), verNumber=number/9.0)
   print "%(capText)s %(verNumber).1f rules!" % params()
or even something like
   print "%(capText)s %(verNumber).1f rules!" % vars()
but it might be even better to use a real templating system
such as cheetah etc. See
http://www.python.org/cgi-bin/moinmoin/WebProgramming#head-9d0636d6da8e88f8f09de1454c5961b44183b04d

Eval might look neat, but I think you will end up missing
the syntax coloring of your python statements if you put
them in strings, and that it will turn out to be trickier
to find bugs.


--
Magnus Lycka (It's really Lyck&aring;), magnus at thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 




More information about the Tutor mailing list