Use eval() safely?

Jonathan Gardner jgardner at
Mon Feb 22 20:45:10 CET 2010

On Sun, Feb 21, 2010 at 1:25 PM, W. Martin Borgert <debacle at> wrote:
> I know that this issue has been discussed before, but most of
> the time using only one argument to eval().
> Is it possible to use the following code, e.g. run as part of a
> web application, to break in and if so, how?
> import math
> def myeval(untrustedinput):
>    return eval(untrustedinput, {"__builtins__": None},
>                { "abs": abs, "sin": math.sin })
> Is it possible to define functions or import modules from the
> untrusted input string?
> Which Python built-ins and math functions would I have to add to
> the functions dictionary to make it unsafe?

Why would you ever run untrusted code on any machine in any language,
let alone Python?

If you're writing a web app, make it so that you only run trusted
code. That is, code installed by the admin, or approved by the admin.

Jonathan Gardner
jgardner at

More information about the Python-list mailing list