safe eval of moderately simple math expressions

Aaron Brady castironpi at
Thu Apr 9 18:55:02 CEST 2009

On Apr 9, 10:56 am, Joel Hedlund <joel.hedl... at> wrote:
> Hi all!
> I'm writing a program that presents a lot of numbers to the user, and I
> want to let the user apply moderately simple arithmentics to these
> numbers. One possibility that comes to mind is to use the eval function,
> but since that sends up all kinds of warning flags in my head, I thought
> I'd put my idea out here first so you guys can tell me if I'm insane. :-)
> This is the gist of it:
> def calc(expr, x):
>      if '_' in expr:
>          raise ValueError("expr must not contain '_' characters")
> I assume there's lots of nasty and absolutely lethal stuff that I've
> missed, and I kindly request you show me the error of my ways.
> Thank you for your time!
> /Joel Hedlund

Would you be willing to examine a syntax tree to determine if there
are any class accesses?  Would it work?

More information about the Python-list mailing list