Simple and safe evaluator

Paul McGuire ptmcg at austin.rr.com
Thu Jun 12 02:25:51 CEST 2008


On Jun 11, 3:25 pm, bvdp <b... at mellowood.ca> 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?
>
> I'm feeling too lazy to write/debug my own parser for this :)
>
> Thanks, Bob.

This example ships with pyparsing, and can be extended to support
built-in functions: http://pyparsing.wikispaces.com/space/showimage/fourFn.py.

-- Paul



More information about the Python-list mailing list