Simple and safe evaluator

Hans Nowak zephyrfalcon!NO_SPAM! at gmail.com
Thu Jun 12 13:50:49 CEST 2008


bvdp wrote:
> 
> Is there a simple/safe expression evaluator I can use in a python 
> program. I just want to pass along a string in the form "1 + 44 / 3" or 
> perhaps "1 + (-4.3*5)" and get a numeric result.
> 
> I can do this with eval() but I really don't want to subject my users to 
> the problems with that method.
> 
> In this use I don't need python to worry about complex numbers, 
> variables or anything else. Just do the math on a set of values. Would 
> eval() with some restricted list of permitted operators do the trick?

This solution may be overly simply (especially compared to the AST-based 
solution suggested earlier), but... if all you need is numbers and operators, 
*maybe* you can get away with stripping all letters from the input string (and 
possibly the underscore), and then evaluating it:


import re
import traceback

re_letters = re.compile("[a-zA-Z_]+")

def safe_eval(s):
     s = re_letters.sub("", s)
     return eval(s)

# try it out...

 >>> safe_eval("2+2")
4

 >>> safe_eval("4 * (8 / 3.1) ** 7.2")
3685.5618352828474

 >>> safe_eval("(2).__class__.__base__.__subclasses__()")
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "safe_eval.py", line 12, in safe_eval
     return eval(s)
   File "<string>", line 1
     (2)...()
         ^
SyntaxError: invalid syntax

...It's primitive, but it might work for your purposes.

-- 
Hans Nowak (zephyrfalcon at gmail dot com)
http://4.flowsnake.org/



More information about the Python-list mailing list