Simple and safe evaluator

sweeneym at acm.org sweeneym at acm.org
Mon Jun 16 22:38:31 EDT 2008


On Jun 17, 8:02 am, bvdp <b... at mellowood.ca> wrote:

> Thanks. That was easy :)
>
> > The change to the _ast version is left as an exercise to the reader ;)
>
> And I have absolutely no idea on how to do this. I can't even find the
> _ast import file on my system. I'm assuming that the _ast definitions
> are buried in the C part of python, but that is just a silly guess.
>
> Bob.

If you just need numeric expressions with a small number of functions,
I would suggest checking the expression string first with a simple
regular expression, then using the standard eval() to evaluate the
result.  This blocks the attacks mentioned above, and is simple to
implement.  This will not work if you want to allow string values in
expressions though.

import re
def safe_eval( expr, safe_cmds=[] ):
	toks = re.split( r'([a-zA-Z_\.]+|.)', expr )
	bad = [t for t in toks if len(t)>1 and t not in safe_cmds]
	if not bad:
		return eval( expr )

>>> safe_eval( "abs(5*-77+33.1) + (int(405.3) * 5.7e-12)", 'int float sum abs'.split() )
351.9000000023085
>>> safe_eval( "abs(5*-77+33.1) + (int(405.3) * 5.7e-12)" )
>>> safe_eval( "open('thesis.tex').write('')" )
>>>

Mike.



More information about the Python-list mailing list