On Jun 11, 1:25 pm, bvdp <[EMAIL PROTECTED]> 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. Regards, ~Simon -- http://mail.python.org/mailman/listinfo/python-list