safe eval of moderately simple math expressions

Peter Otten __peter__ at web.de
Sat Apr 11 10:38:32 CEST 2009


Joel Hedlund wrote:

> Matt Nordhoff wrote:
>>>>> '\x5f'
>> '_'
>>>>> getattr(42, '\x5f\x5fclass\x5f\x5f') # __class__
>> <type 'int'>
>> 
>> Is that enough to show you the error of your ways?
> 
> No, because
> 
>  >>> print '_' in '\x5f\x5fclass\x5f\x5f'
> True

But what you're planning to do seems more like

>>> def is_it_safe(source):
...     return "_" not in source
...
>>> source = "getattr(42, '\\x5f\\x5fclass\\x5f\\x5f')"
>>> if is_it_safe(source):
...     print eval(source)
...
<type 'int'>

Peter



More information about the Python-list mailing list