Is Eval *always* Evil?

John Nagle nagle at animats.com
Thu Nov 11 03:07:53 EST 2010


On 11/10/2010 6:39 PM, Robert Kern wrote:
> On 2010-11-10 17:14 , Christian Heimes wrote:
>> Am 10.11.2010 18:56, schrieb Simon Mullis:
>>
>> Yes, eval is evil, may lead to security issues and it's unnecessary
>> slow, too.

    If you have to use "eval", use the 2 or 3 argument form with a
"globals" and "locals" dictionary.  This lists the variables
and functions that "eval" can see and touch.

    The Python documentation for this is not very good:
"If the globals dictionary is present and lacks ‘__builtins__’, the 
current globals are copied into globals before expression is parsed. 
This means that expression  normally has full access to the standard 
__builtin__  module and restricted environments are propagated."

    What this means is that you have to put in "__builtins__" to
PREVENT all built-ins from being imported.

See

   http://lybniz2.sourceforge.net/safeeval.html

for something readable on how to use "eval" safely.

				John Nagle



More information about the Python-list mailing list