Re: Simple and safe evaluator



George Sakkis wrote:
On Jun 16, 4:47 pm, bvdp <b...@xxxxxxxxxxxx> wrote:

2. I thought I'd be happy with * / + -, etc. Of course now I want to add
a few more funcs like int() and sin(). How would I do that?

For the builtin eval, just populate the globals dict with the names
you want to make available:

import math

globs = {'__builtins__' : None}

# expose selected builtins
for name in 'True False int float round abs divmod'.split():
globs[name] = eval(name)

# expose selected math constants and functions
for name in 'e pi sqrt exp log ceil floor sin cos tan'.split():
globs[name] = getattr(math,name)

return eval(s, globs, {})


Thanks. That was easy :)

The change to the _ast version is left as an exercise to the reader ;)

And I have absolutely no idea on how to do this. I can't even find the _ast import file on my system. I'm assuming that the _ast definitions are buried in the C part of python, but that is just a silly guess.

Bob.
.



Relevant Pages

  • Re: [ANNOUNCE] System Inactivity Monitor v1.0
    ... this options lets you to specify how much frequently SIN should be ... static struct timer_list timer; ... static int shutdown; ...
    (Linux-Kernel)
  • Re: Algorithms in C - Robert Sedgewick
    ... one would expect element of an array to hold something ... int search(int a, int v, int l, int r) { ... Math always seemed incomprehensible to me. ... Before discovered the law of gravitation, ...
    (comp.lang.c)
  • Re: integers and arrays in Java - how?
    ... Get X and Y mouse coordinates into a variable that i can do real math on. ... If i try "int" in that math, the values are then zero for everything - even those where i do no calculation. ... var with "Netscape" makes Netscape happy ...
    (comp.lang.java)
  • Re: integers and arrays in Java - how?
    ... Get X and Y mouse coordinates into a variable that i can do real math on. ... If i try "int" in that math, the values are then zero for everything - even those where i do no calculation. ... var with "Netscape" makes Netscape happy ...
    (comp.lang.java)
  • Re: integers and arrays inJava - how?
    ... Get X and Y mouse coordinates into a variable that i can do real math on. ... If i try "int" in that math, the values are then zero for everything - even those where i do no calculation. ... var with "Netscape" makes Netscape happy ...
    (comp.lang.java.help)