Turning String into Numerical Equation

Giovanni Bajo noway at sorry.com
Tue Mar 15 21:23:19 EST 2005


Steven Bethard wrote:

>>> 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'>
>
> Yeah, I was concerned about the same thing, but I realized that I
> can't actually access any of the func_globals attributes:


When __builtin__ is not the standard __builtin__, Python is in restricted
execution mode. In fact, I believe my solution to be totally safe, and I
otherwise would love to be proved wrong.
-- 
Giovanni Bajo





More information about the Python-list mailing list