safe eval of moderately simple math expressions

Peter Otten __peter__ at web.de
Sat Apr 11 05:19:41 EDT 2009


Joel Hedlund wrote:

> Peter Otten wrote:
>> 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'>
> 
> Bah. You are completely right of course.
> 
> Just as a thought experiment, would this do the trick?
> 
> def is_it_safe(source):
>      return "_" not in source and r'\' not in source

>>> "".join(map(chr, [95, 95, 110, 111, 95, 95]))
'__no__'

By the way, a raw string may not end with a backslash:

>>> r'\'
  File "<stdin>", line 1
    r'\'
       ^
SyntaxError: EOL while scanning single-quoted string

Peter



More information about the Python-list mailing list