Simple and safe evaluator
bob at mellowood.ca
Wed Jun 11 23:53:41 CEST 2008
Simon Forman wrote:
> On Jun 11, 1: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.
> Funny, I need exactly the same kind of parser myself right now.
> Fredrik Lundh has posted some code-and-explanation on an excellent
> simple parser that's easy to extend. http://effbot.org/zone/simple-iterator-parser.htm
> Just make it recognize the operator tokens you're interested in and if
> a string parsers w/o errors then you know it's safe to eval().
> I probably won't get to writing this myself for a few days or a week,
> but if you do will you post it here (or send me a copy)? I'll do the
> same if I get to it sooner.
I'll have to read Fredrik's code a few more times, but I think it makes
as much sense as anything else. Of course, I could take the lazy man's
way out and just to a left->right evaluation without any ()s, etc.,
which in my project would work. But, honestly, I thought it'd be easier.
I was going to use eval() until I realized that it was not a good idea.
Darn shame we have to work so hard to prevent some jerk's malicious code
from effecting our stuff. Oh well, that's life.
More information about the Python-list