eval vs. exec

Simon Budig Simon.Budig at unix-ag.org
Mon May 27 12:38:31 EDT 2002


Alexander Schmolck <a.schmolck at gmx.net> wrote:
> Simon Budig <Simon.Budig at unix-ag.org> writes:
> 
> 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 :)

I think I do know what an expression is - what I do not know is
how to determine the type to use from a string given by an external
source.

[...]
> 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"]

The strings are from an external source, so I have no control over them.

> 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.

I think I took quite good care of it by making sure that before I
eval/exec something the mathdict["__builtins__"] = {}. In the real code
I also have a runtime control so that "100L**(100L**100L)" would not
virtually stop the program.

> 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.

I do know about this, but this is definitely necessary because otherwise
it would be possible to crash the program via "raise 'foo'".

Thanks,
        Simon
-- 
      Simon.Budig at unix-ag.org       http://www.home.unix-ag.org/simon/



More information about the Python-list mailing list