Simple and safe evaluator

Grant Edwards grante at visi.com
Thu Jun 12 10:13:41 EDT 2008


On 2008-06-12, Hans Nowak <zephyrfalcon!NO_SPAM!@gmail.com> wrote:
> 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:

It won't work for numbers expressed in scientific notation
(e.g. 1.23e-3).

-- 
Grant Edwards                   grante             Yow! All right, you
                                  at               degenerates!  I want
                               visi.com            this place evacuated in
                                                   20 seconds!



More information about the Python-list mailing list