[Tutor] avoid eval how???

Colin J. Williams cjw at sympatico.ca
Fri Nov 4 02:52:45 CET 2005


Danny Yoo wrote:

>>You make some good points here but I suggest that, in the real world,
>>the risks are small.
>>    
>>
>
>Hi Colin,
>
>But that's the point I'm trying to make; eval() is appropriate only for
>toy code.  In real world code that's exposed to the world, using eval() is
>usually the wrong thing to do, because it really is dangerous unless we
>really know what we're doing.
>
>
>eval() is more potent than it appears.  We had a thread about this last
>year:
>
>    http://mail.python.org/pipermail/tutor/2004-December/033819.html
>    http://mail.python.org/pipermail/tutor/2004-December/033828.html
>
>I gave an an example that shows that it's very possible to write an
>infinite loop (or at least hit Python's stack limit) with a single
>expression:
>
>######
>s = "(lambda loop: loop(loop)) (lambda self: self(self))"
>eval(s)
>######
>
>Note that there are no calls to the builtins, nor any reference to outside
>free variables.  It's just simple function application.
>
>
>Beginners see eval() as an easy all-in-one tool for doing parsing and
>value conversion.  Those who use it indiscriminately don't understand that
>Python's eval() has enough power to do bad things like infinite loops and
>calls to os.system().
>
>
>  
>
>>You might consider using exec instead.  It would appear that one can
>>specify a restricted environment in which the statement is executed.
>>    
>>
>
>I think you're talking about 'rexec'.  But the folks who finally wrote the
>Python Standard Library eventually woke up and deprecated rexec.
>
>    http://www.python.org/doc/lib/module-rexec.html
>
>They deprecated it because they could not guarantee a safe, restricted
>execution environment on top of Python's eval() and exec primitives.
>
>  
>
Hi Danny,

No, I was thinking of exec.  The given statement can be executed in a 
specified environment.
You might say "The rogue code can dodge that with an import statement 
with an import".

True, but it seems to me that a user specified __import__ function can 
protect against this.

I have not tried this.

>I'm not saying that eval() is useless: it does have its uses.  And I
>suppose that it's possible to write sandboxes if we're cautious enough
>with it.  My point, though, is that it is not trivial to make eval()/exec
>safe.  Plenty of smart people have tried it and messed it up.  I'm dumb
>enough not to try.  *grin*
>
>  
>
I accept the points you make wrt eval.

Colin W.

>There are plenty of other alternatives for turning a string into dynamic
>"code".  I'd rather we concentrate on those because such techniques are
>well known and battle tested.
>
>
>Hope this helps!
>
>  
>



More information about the Tutor mailing list