Yet another attempt at a safe eval() call
invalid at invalid.invalid
Fri Jan 4 18:14:36 CET 2013
On 2013-01-04, Chris Angelico <rosuav at gmail.com> wrote:
> On Sat, Jan 5, 2013 at 3:38 AM, Grant Edwards <invalid at invalid.invalid> wrote:
>> I've added equals, backslash, commas, square/curly brackets, colons
>> and semicolons to the prohibited character list. I also reduced the
>> maximum length to 60 characters. It's unfortunate that parentheses
>> are overloaded for both expression grouping and for function
> I have to say that an expression evaluator that can't handle parens
> for grouping is badly flawed.
Indeed. That's why I didn't disallow parens.
What I was implying was that since you have to allow parens for
grouping, there's no simple way to disallow function calls.
> Can you demand that open parenthesis be preceded by an operator (or
> beginning of line)?
Yes, but once you've parsed the expression to the point where you can
enforce rules like that, you're probably most of the way to doing the
"right" thing and evaluating the expression using ast or pyparsing or
> You can probably recognize the formula I'm working with there, but
> it's far less obvious and involves six separate statements rather than
> two. And this is a fairly simple formula. It'll get a lot worse in
In the general case, yes. For this assembler I could _probably_ get
by with expressions of the form <symbol> <op> <literal> where op is
'+' or '-'. But, whenever I try to come up with a minimal solution
like that, it tends to get "enhanced" over the years until it's a
complete mess, doesn't work quite right, and took more total man-hours
than a general and "permanent" solution would have.
Some might argue that repeated tweaking of and adding limitiations to
a "safe eval" is just heading down that same road in a different car.
They'd probably be right: in the end, it will probably have been less
work to just do it with ast. But it's still interesting to try. :)
Grant Edwards grant.b.edwards Yow! Are you the
at self-frying president?
More information about the Python-list