eval(source, {'builtins': {}}) archived as Faq

Erik Max Francis max at alcyone.com
Fri Sep 29 01:28:45 CEST 2006

p.lavarre at ieee.org wrote:

> Absent from http://www.python.org/doc/current/lib/built-in-funcs.html
> but now copied to the Faq list of http://pyfaq.infogami.com/suggest,
> from these clp archives:
> ///
> Q: How can I tell Python to calculate what quoted strings and numbers
> mean, without also accidentally accepting OS commands as input?
> A: eval(source, {'builtins': {}})
> Note: What eval may do to you remains as surprising as ever if you
> mistype this idiom as: eval(source, {})
> Note: This idiom makes sense of ordinary Python literals (such as 010,
> 0x8, 8.125e+0, and "\x45ight").  This idiom also correctly interprets
> simple literal expressions, such as 64**0.5.

This is an _extremely_ bad idea.  _Never_ use eval in a case where you 
are trying to validate input.

 >>> def e(source): return eval(source, {'builtins': {}})
 >>> e('__import__("sys").exit()')

Oops, the interpreter exited.

Just when you think you've covered all the bases, you haven't.

Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   A man's life is what his thoughts make it.
    -- Marcus Aurelius

More information about the Python-list mailing list