Turning String into Numerical Equation

Michael Spencer mahs at telcopartners.com
Tue Mar 15 00:50:56 EST 2005


Giovanni Bajo wrote:
> Michael Spencer wrote:
> 
> 
>>* this means that, eval("sys.exit()") will likely stop your
>>interpreter, and
>>there are various other inputs with possibly harmful consequences.
>>
>>Concerns like these may send you back to your original idea of doing
>>your own expression parsing.
> 
> 
> I use something along these lines:
> 
> def safe_eval(expr, symbols={}):
>     return eval(expr, dict(__builtins__=None, True=True, False=False), symbols)
> 
> import math
> def calc(expr):
>     return safe_eval(expr, vars(math))
> 
That offers only notional security:

  >>> calc("acos.__class__.__bases__[0]")
  <type 'object'>

...

Michael





More information about the Python-list mailing list