Simple and safe evaluator
zephyrfalcon!NO_SPAM! at gmail.com
Thu Jun 12 13:50:49 CEST 2008
> 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:
re_letters = re.compile("[a-zA-Z_]+")
s = re_letters.sub("", s)
# try it out...
>>> safe_eval("4 * (8 / 3.1) ** 7.2")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "safe_eval.py", line 12, in safe_eval
File "<string>", line 1
SyntaxError: invalid syntax
...It's primitive, but it might work for your purposes.
Hans Nowak (zephyrfalcon at gmail dot com)
More information about the Python-list