Simple and safe evaluator

bvdp bob at
Thu Jun 12 02:15:49 CEST 2008

Matimus wrote:

> The solution I posted should work and is safe. It may not seem very
> readable, but it is using Pythons internal parser to parse the passed
> in string into an abstract symbol tree (rather than code). Normally
> Python would just use the ast internally to create code. Instead I've
> written the code to do that. By avoiding anything but simple operators
> and literals it is guaranteed safe.

Just wondering ... how safe would:

	 eval(s, {"__builtins__":None}, {} )

be? From my testing it seems that it parses out numbers properly (int 
and float) and does simple math like +, -, **, etc. It doesn't do 
functions like int(), sin(), etc ... but that is fine for my puposes.

Just playing a bit, it seems to give the same results as your code using 
ast does. I may be missing something!

More information about the Python-list mailing list