eval vs. exec

Alexander Schmolck a.schmolck at gmx.net
Mon May 27 10:13:04 EDT 2002


Simon Budig <Simon.Budig at unix-ag.org> writes:

> Hi.
> 
> I currently have problems to let code inside strings execute as I want
> to have it. Especially the difference between "eval" and "exec"
> (resp. compiling as 'eval' or as 'single') makes me headache.
> I want to execute things like the three following strings:
> 
> "a = 2"           ---> returns nothing
> "3 * 4"           ---> returns 12
> "a=2; b=3; a*b"   ---> returns 6


The distiction is quite simple: use eval for expressions and exec for
everything else. That of course only works if you know what qualifies as an
expression in python :)

Maybe this helps: an expression is something that returns a value, so anything
you can write on the right side of an '=' is an expression (unless it already
has an "=" in it) and everything you can't isn't. So only example 2 above is
an expression. If you have an expression, use eval, else use exec, which will
execute arbitrary code in the dictionary you specify with "in" (default
globals, but I'd never use that).

This will work fine for case 2:

result = eval("3 * 4") 

for the other cases a not completely horrible way to do it is:

namespace = {}
exec "a=2; b=3; result=a*b" in namespace
result = namespace["result"]

or even better, depending on how much control you have over the strings do:

result = eval("a*b", {"a" : 2, "b" : 3})

Of course using eval or exec is usually not a good idea, because it creates a
huge security risk -- A better approach would be to parse the expression or at
least make sure it only contains harmless things before you exec/eval it.


BTW: this

>       except:

is almost always a bad idea. You should explicitly test for the Errors you are
expecting like so: 

         except SyntaxError:
         
because otherwise bugs you didn't expect might go unnoticed.

HTH

alex



More information about the Python-list mailing list